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
1156pub struct AgentDiff {
1157    reviewing_editors: HashMap<WeakEntity<Editor>, EditorState>,
1158    workspace_threads: HashMap<WeakEntity<Workspace>, WorkspaceThread>,
1159    _settings_subscription: Subscription,
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    _workspace_subscription: Option<Subscription>,
1174}
1175
1176struct AgentDiffGlobal(Entity<AgentDiff>);
1177
1178impl Global for AgentDiffGlobal {}
1179
1180impl AgentDiff {
1181    fn global(cx: &mut App) -> Entity<Self> {
1182        cx.try_global::<AgentDiffGlobal>()
1183            .map(|global| global.0.clone())
1184            .unwrap_or_else(|| {
1185                let entity = cx.new(Self::new);
1186                let global = AgentDiffGlobal(entity.clone());
1187                cx.set_global(global);
1188                entity.clone()
1189            })
1190    }
1191
1192    fn new(cx: &mut Context<Self>) -> Self {
1193        let mut was_active = AssistantSettings::get_global(cx).single_file_review;
1194        let settings_subscription = cx.observe_global::<SettingsStore>(move |this, cx| {
1195            let is_active = AssistantSettings::get_global(cx).single_file_review;
1196
1197            if was_active != is_active {
1198                let workspaces = this.workspace_threads.keys().cloned().collect::<Vec<_>>();
1199                for workspace in workspaces {
1200                    this.update_reviewing_editors(&workspace, cx);
1201                }
1202            }
1203
1204            was_active = is_active;
1205        });
1206
1207        Self {
1208            reviewing_editors: HashMap::default(),
1209            workspace_threads: HashMap::default(),
1210            _settings_subscription: settings_subscription,
1211        }
1212    }
1213
1214    pub fn set_active_thread(
1215        workspace: &WeakEntity<Workspace>,
1216        thread: &Entity<Thread>,
1217        cx: &mut App,
1218    ) {
1219        Self::global(cx).update(cx, |this, cx| {
1220            this.register_active_thread_impl(workspace, thread, cx);
1221        });
1222    }
1223
1224    fn register_active_thread_impl(
1225        &mut self,
1226        workspace: &WeakEntity<Workspace>,
1227        thread: &Entity<Thread>,
1228        cx: &mut Context<Self>,
1229    ) {
1230        let agent_diff = cx.entity();
1231        let action_log = thread.read(cx).action_log().clone();
1232
1233        let action_log_subscription = cx.observe(&action_log, {
1234            let workspace = workspace.clone();
1235            move |this, _action_log, cx| {
1236                this.update_reviewing_editors(&workspace, cx);
1237            }
1238        });
1239
1240        let thread_subscription = cx.subscribe(&thread, {
1241            let workspace = workspace.clone();
1242            move |this, _thread, event, cx| this.handle_thread_event(&workspace, event, cx)
1243        });
1244
1245        if let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) {
1246            // replace thread and action log subscription, but keep editors
1247            workspace_thread.thread = thread.downgrade();
1248            workspace_thread._thread_subscriptions = [action_log_subscription, thread_subscription];
1249            self.update_reviewing_editors(&workspace, cx);
1250            return;
1251        }
1252
1253        let workspace_subscription = workspace
1254            .upgrade()
1255            .map(|workspace| cx.subscribe(&workspace, Self::handle_workspace_event));
1256
1257        self.workspace_threads.insert(
1258            workspace.clone(),
1259            WorkspaceThread {
1260                thread: thread.downgrade(),
1261                _thread_subscriptions: [action_log_subscription, thread_subscription],
1262                singleton_editors: HashMap::default(),
1263                _workspace_subscription: workspace_subscription,
1264            },
1265        );
1266
1267        let workspace = workspace.clone();
1268        cx.defer(move |cx| {
1269            if let Some(strong_workspace) = workspace.upgrade() {
1270                agent_diff.update(cx, |this, cx| {
1271                    this.register_workspace(strong_workspace, cx);
1272                })
1273            }
1274        });
1275    }
1276
1277    fn register_workspace(&mut self, workspace: Entity<Workspace>, cx: &mut Context<Self>) {
1278        let agent_diff = cx.entity();
1279
1280        let editors = workspace.update(cx, |workspace, cx| {
1281            let agent_diff = agent_diff.clone();
1282
1283            Self::register_review_action::<Keep>(workspace, Self::keep, &agent_diff);
1284            Self::register_review_action::<Reject>(workspace, Self::reject, &agent_diff);
1285            Self::register_review_action::<KeepAll>(workspace, Self::keep_all, &agent_diff);
1286            Self::register_review_action::<RejectAll>(workspace, Self::reject_all, &agent_diff);
1287
1288            workspace.items_of_type(cx).collect::<Vec<_>>()
1289        });
1290
1291        let weak_workspace = workspace.downgrade();
1292
1293        for editor in editors {
1294            if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1295                self.register_editor(weak_workspace.clone(), buffer, editor, cx);
1296            };
1297        }
1298
1299        self.update_reviewing_editors(&weak_workspace, cx);
1300    }
1301
1302    fn register_review_action<T: Action>(
1303        workspace: &mut Workspace,
1304        review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState
1305        + 'static,
1306        this: &Entity<AgentDiff>,
1307    ) {
1308        let this = this.clone();
1309        workspace.register_action(move |workspace, _: &T, window, cx| {
1310            let review = &review;
1311            let task = this.update(cx, |this, cx| {
1312                this.review_in_active_editor(workspace, review, window, cx)
1313            });
1314
1315            if let Some(task) = task {
1316                task.detach_and_log_err(cx);
1317            } else {
1318                cx.propagate();
1319            }
1320        });
1321    }
1322
1323    fn handle_thread_event(
1324        &mut self,
1325        workspace: &WeakEntity<Workspace>,
1326        event: &ThreadEvent,
1327        cx: &mut Context<Self>,
1328    ) {
1329        match event {
1330            ThreadEvent::NewRequest
1331            | ThreadEvent::Stopped(Ok(StopReason::EndTurn))
1332            | ThreadEvent::Stopped(Ok(StopReason::MaxTokens))
1333            | ThreadEvent::Stopped(Err(_))
1334            | ThreadEvent::ShowError(_)
1335            | ThreadEvent::CompletionCanceled => {
1336                self.update_reviewing_editors(workspace, cx);
1337            }
1338            // intentionally being exhaustive in case we add a variant we should handle
1339            ThreadEvent::Stopped(Ok(StopReason::ToolUse))
1340            | ThreadEvent::UsageUpdated(_)
1341            | ThreadEvent::StreamedCompletion
1342            | ThreadEvent::ReceivedTextChunk
1343            | ThreadEvent::StreamedAssistantText(_, _)
1344            | ThreadEvent::StreamedAssistantThinking(_, _)
1345            | ThreadEvent::StreamedToolUse { .. }
1346            | ThreadEvent::InvalidToolInput { .. }
1347            | ThreadEvent::MessageAdded(_)
1348            | ThreadEvent::MessageEdited(_)
1349            | ThreadEvent::MessageDeleted(_)
1350            | ThreadEvent::SummaryGenerated
1351            | ThreadEvent::SummaryChanged
1352            | ThreadEvent::UsePendingTools { .. }
1353            | ThreadEvent::ToolFinished { .. }
1354            | ThreadEvent::CheckpointChanged
1355            | ThreadEvent::ToolConfirmationNeeded
1356            | ThreadEvent::CancelEditing => {}
1357        }
1358    }
1359
1360    fn handle_workspace_event(
1361        &mut self,
1362        workspace: Entity<Workspace>,
1363        event: &workspace::Event,
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(workspace.downgrade(), buffer.clone(), editor, cx);
1371                    }
1372                }
1373            }
1374            _ => {}
1375        }
1376    }
1377
1378    fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1379        if editor.mode().is_full() {
1380            editor
1381                .buffer()
1382                .read(cx)
1383                .as_singleton()
1384                .map(|buffer| buffer.downgrade())
1385        } else {
1386            None
1387        }
1388    }
1389
1390    fn register_editor(
1391        &mut self,
1392        workspace: WeakEntity<Workspace>,
1393        buffer: WeakEntity<Buffer>,
1394        editor: Entity<Editor>,
1395        cx: &mut Context<Self>,
1396    ) {
1397        let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1398            return;
1399        };
1400
1401        let weak_editor = editor.downgrade();
1402
1403        workspace_thread
1404            .singleton_editors
1405            .entry(buffer.clone())
1406            .or_default()
1407            .entry(weak_editor.clone())
1408            .or_insert_with(|| {
1409                let workspace = workspace.clone();
1410                cx.observe_release(&editor, move |this, _, _cx| {
1411                    let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1412                        return;
1413                    };
1414
1415                    if let Entry::Occupied(mut entry) =
1416                        active_thread.singleton_editors.entry(buffer)
1417                    {
1418                        let set = entry.get_mut();
1419                        set.remove(&weak_editor);
1420
1421                        if set.is_empty() {
1422                            entry.remove();
1423                        }
1424                    }
1425                })
1426            });
1427
1428        self.update_reviewing_editors(&workspace, cx);
1429    }
1430
1431    fn update_reviewing_editors(
1432        &mut self,
1433        workspace: &WeakEntity<Workspace>,
1434        cx: &mut Context<Self>,
1435    ) {
1436        if !AssistantSettings::get_global(cx).single_file_review {
1437            for (editor, _) in self.reviewing_editors.drain() {
1438                editor
1439                    .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1440                    .ok();
1441            }
1442            return;
1443        }
1444
1445        let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1446            return;
1447        };
1448
1449        let Some(thread) = workspace_thread.thread.upgrade() else {
1450            return;
1451        };
1452
1453        let action_log = thread.read(cx).action_log();
1454        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1455
1456        let mut unaffected = self.reviewing_editors.clone();
1457
1458        for (buffer, diff_handle) in changed_buffers {
1459            if buffer.read(cx).file().is_none() {
1460                continue;
1461            }
1462
1463            let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1464            else {
1465                continue;
1466            };
1467
1468            for (weak_editor, _) in buffer_editors {
1469                let Some(editor) = weak_editor.upgrade() else {
1470                    continue;
1471                };
1472
1473                let multibuffer = editor.read(cx).buffer().clone();
1474                multibuffer.update(cx, |multibuffer, cx| {
1475                    multibuffer.add_diff(diff_handle.clone(), cx);
1476                });
1477
1478                let new_state = if thread.read(cx).is_generating() {
1479                    EditorState::Generating
1480                } else {
1481                    EditorState::Reviewing
1482                };
1483
1484                let previous_state = self
1485                    .reviewing_editors
1486                    .insert(weak_editor.clone(), new_state.clone());
1487
1488                if previous_state.is_none() {
1489                    editor.update(cx, |editor, cx| {
1490                        editor.start_temporary_diff_override();
1491                        editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
1492                        editor.set_expand_all_diff_hunks(cx);
1493                        editor.register_addon(EditorAgentDiffAddon);
1494                    });
1495                } else {
1496                    unaffected.remove(&weak_editor);
1497                }
1498
1499                if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
1500                    if let Some(workspace) = workspace.upgrade() {
1501                        let workspace_id = workspace.entity_id();
1502                        let workspace_window = cx.windows().iter().find_map(|w| {
1503                            w.downcast::<Workspace>().and_then(|window_workspace| {
1504                                if window_workspace
1505                                    .entity(cx)
1506                                    .map_or(false, |entity| entity.entity_id() == workspace_id)
1507                                {
1508                                    Some(window_workspace)
1509                                } else {
1510                                    None
1511                                }
1512                            })
1513                        });
1514
1515                        if let Some(workspace_window) = workspace_window {
1516                            workspace_window
1517                                .update(cx, |_, window, cx| {
1518                                    editor.update(cx, |editor, cx| {
1519                                        editor.go_to_next_hunk(&GoToHunk, window, cx);
1520                                    });
1521                                })
1522                                .log_err();
1523                        }
1524                    }
1525                }
1526            }
1527        }
1528
1529        // Remove editors from this workspace that are no longer under review
1530        for (editor, _) in unaffected {
1531            // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1532            // but that would add another lookup in `AgentDiff::editor_state`
1533            // which gets called much more frequently.
1534            let in_workspace = editor
1535                .read_with(cx, |editor, _cx| editor.workspace())
1536                .ok()
1537                .flatten()
1538                .map_or(false, |editor_workspace| {
1539                    editor_workspace.entity_id() == workspace.entity_id()
1540                });
1541
1542            if in_workspace {
1543                editor
1544                    .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1545                    .ok();
1546                self.reviewing_editors.remove(&editor);
1547            }
1548        }
1549
1550        cx.notify();
1551    }
1552
1553    fn editor_state(&self, editor: &Entity<Editor>) -> &EditorState {
1554        self.reviewing_editors
1555            .get(&editor.downgrade())
1556            .unwrap_or(&EditorState::Idle)
1557    }
1558
1559    fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1560        let Some(workspace) = editor.read(cx).workspace() else {
1561            return;
1562        };
1563
1564        let Some(WorkspaceThread { thread, .. }) =
1565            self.workspace_threads.get(&workspace.downgrade())
1566        else {
1567            return;
1568        };
1569
1570        let Some(thread) = thread.upgrade() else {
1571            return;
1572        };
1573
1574        AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1575    }
1576
1577    fn keep_all(
1578        editor: &Entity<Editor>,
1579        thread: &Entity<Thread>,
1580        window: &mut Window,
1581        cx: &mut App,
1582    ) -> PostReviewState {
1583        editor.update(cx, |editor, cx| {
1584            let snapshot = editor.buffer().read(cx).snapshot(cx);
1585            keep_edits_in_ranges(
1586                editor,
1587                &snapshot,
1588                thread,
1589                vec![editor::Anchor::min()..editor::Anchor::max()],
1590                window,
1591                cx,
1592            );
1593        });
1594        PostReviewState::AllReviewed
1595    }
1596
1597    fn reject_all(
1598        editor: &Entity<Editor>,
1599        thread: &Entity<Thread>,
1600        window: &mut Window,
1601        cx: &mut App,
1602    ) -> PostReviewState {
1603        editor.update(cx, |editor, cx| {
1604            let snapshot = editor.buffer().read(cx).snapshot(cx);
1605            reject_edits_in_ranges(
1606                editor,
1607                &snapshot,
1608                thread,
1609                vec![editor::Anchor::min()..editor::Anchor::max()],
1610                window,
1611                cx,
1612            );
1613        });
1614        PostReviewState::AllReviewed
1615    }
1616
1617    fn keep(
1618        editor: &Entity<Editor>,
1619        thread: &Entity<Thread>,
1620        window: &mut Window,
1621        cx: &mut App,
1622    ) -> PostReviewState {
1623        editor.update(cx, |editor, cx| {
1624            let snapshot = editor.buffer().read(cx).snapshot(cx);
1625            keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1626            Self::post_review_state(&snapshot)
1627        })
1628    }
1629
1630    fn reject(
1631        editor: &Entity<Editor>,
1632        thread: &Entity<Thread>,
1633        window: &mut Window,
1634        cx: &mut App,
1635    ) -> PostReviewState {
1636        editor.update(cx, |editor, cx| {
1637            let snapshot = editor.buffer().read(cx).snapshot(cx);
1638            reject_edits_in_selection(editor, &snapshot, thread, window, cx);
1639            Self::post_review_state(&snapshot)
1640        })
1641    }
1642
1643    fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1644        for (i, _) in snapshot.diff_hunks().enumerate() {
1645            if i > 0 {
1646                return PostReviewState::Pending;
1647            }
1648        }
1649        PostReviewState::AllReviewed
1650    }
1651
1652    fn review_in_active_editor(
1653        &mut self,
1654        workspace: &mut Workspace,
1655        review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState,
1656        window: &mut Window,
1657        cx: &mut Context<Self>,
1658    ) -> Option<Task<Result<()>>> {
1659        let active_item = workspace.active_item(cx)?;
1660        let editor = active_item.act_as::<Editor>(cx)?;
1661
1662        if !matches!(self.editor_state(&editor), EditorState::Reviewing) {
1663            return None;
1664        }
1665
1666        let WorkspaceThread { thread, .. } =
1667            self.workspace_threads.get(&workspace.weak_handle())?;
1668
1669        let thread = thread.upgrade()?;
1670
1671        if let PostReviewState::AllReviewed = review(&editor, &thread, window, cx) {
1672            if let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1673                let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
1674
1675                let mut keys = changed_buffers.keys().cycle();
1676                keys.find(|k| *k == &curr_buffer);
1677                let next_project_path = keys
1678                    .next()
1679                    .filter(|k| *k != &curr_buffer)
1680                    .and_then(|after| after.read(cx).project_path(cx));
1681
1682                if let Some(path) = next_project_path {
1683                    let task = workspace.open_path(path, None, true, window, cx);
1684                    let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1685                    return Some(task);
1686                }
1687            }
1688        }
1689
1690        return Some(Task::ready(Ok(())));
1691    }
1692}
1693
1694enum PostReviewState {
1695    AllReviewed,
1696    Pending,
1697}
1698
1699pub struct EditorAgentDiffAddon;
1700
1701impl editor::Addon for EditorAgentDiffAddon {
1702    fn to_any(&self) -> &dyn std::any::Any {
1703        self
1704    }
1705
1706    fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1707        key_context.add("agent_diff");
1708        key_context.add("editor_agent_diff");
1709    }
1710}
1711
1712#[cfg(test)]
1713mod tests {
1714    use super::*;
1715    use crate::{Keep, ThreadStore, thread_store};
1716    use assistant_settings::AssistantSettings;
1717    use assistant_tool::ToolWorkingSet;
1718    use context_server::ContextServerSettings;
1719    use editor::EditorSettings;
1720    use gpui::TestAppContext;
1721    use project::{FakeFs, Project};
1722    use prompt_store::PromptBuilder;
1723    use serde_json::json;
1724    use settings::{Settings, SettingsStore};
1725    use std::sync::Arc;
1726    use theme::ThemeSettings;
1727    use util::path;
1728
1729    #[gpui::test]
1730    async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1731        cx.update(|cx| {
1732            let settings_store = SettingsStore::test(cx);
1733            cx.set_global(settings_store);
1734            language::init(cx);
1735            Project::init_settings(cx);
1736            AssistantSettings::register(cx);
1737            prompt_store::init(cx);
1738            thread_store::init(cx);
1739            workspace::init_settings(cx);
1740            ThemeSettings::register(cx);
1741            ContextServerSettings::register(cx);
1742            EditorSettings::register(cx);
1743            language_model::init_settings(cx);
1744        });
1745
1746        let fs = FakeFs::new(cx.executor());
1747        fs.insert_tree(
1748            path!("/test"),
1749            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1750        )
1751        .await;
1752        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1753        let buffer_path = project
1754            .read_with(cx, |project, cx| {
1755                project.find_project_path("test/file1", cx)
1756            })
1757            .unwrap();
1758
1759        let prompt_store = None;
1760        let thread_store = cx
1761            .update(|cx| {
1762                ThreadStore::load(
1763                    project.clone(),
1764                    cx.new(|_| ToolWorkingSet::default()),
1765                    prompt_store,
1766                    Arc::new(PromptBuilder::new(None).unwrap()),
1767                    cx,
1768                )
1769            })
1770            .await
1771            .unwrap();
1772        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1773        let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1774
1775        let (workspace, cx) =
1776            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1777        let agent_diff = cx.new_window_entity(|window, cx| {
1778            AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1779        });
1780        let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1781
1782        let buffer = project
1783            .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1784            .await
1785            .unwrap();
1786        cx.update(|_, cx| {
1787            action_log.update(cx, |log, cx| log.track_buffer(buffer.clone(), cx));
1788            buffer.update(cx, |buffer, cx| {
1789                buffer
1790                    .edit(
1791                        [
1792                            (Point::new(1, 1)..Point::new(1, 2), "E"),
1793                            (Point::new(3, 2)..Point::new(3, 3), "L"),
1794                            (Point::new(5, 0)..Point::new(5, 1), "P"),
1795                            (Point::new(7, 1)..Point::new(7, 2), "W"),
1796                        ],
1797                        None,
1798                        cx,
1799                    )
1800                    .unwrap()
1801            });
1802            action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1803        });
1804        cx.run_until_parked();
1805
1806        // When opening the assistant diff, the cursor is positioned on the first hunk.
1807        assert_eq!(
1808            editor.read_with(cx, |editor, cx| editor.text(cx)),
1809            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1810        );
1811        assert_eq!(
1812            editor
1813                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1814                .range(),
1815            Point::new(1, 0)..Point::new(1, 0)
1816        );
1817
1818        // After keeping a hunk, the cursor should be positioned on the second hunk.
1819        agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1820        cx.run_until_parked();
1821        assert_eq!(
1822            editor.read_with(cx, |editor, cx| editor.text(cx)),
1823            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1824        );
1825        assert_eq!(
1826            editor
1827                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1828                .range(),
1829            Point::new(3, 0)..Point::new(3, 0)
1830        );
1831
1832        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1833        editor.update_in(cx, |editor, window, cx| {
1834            editor.change_selections(None, window, cx, |selections| {
1835                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1836            });
1837        });
1838        agent_diff.update_in(cx, |diff, window, cx| {
1839            diff.reject(&crate::Reject, window, cx)
1840        });
1841        cx.run_until_parked();
1842        assert_eq!(
1843            editor.read_with(cx, |editor, cx| editor.text(cx)),
1844            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1845        );
1846        assert_eq!(
1847            editor
1848                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1849                .range(),
1850            Point::new(3, 0)..Point::new(3, 0)
1851        );
1852
1853        // Keeping a range that doesn't intersect the current selection doesn't move it.
1854        agent_diff.update_in(cx, |_diff, window, cx| {
1855            let position = editor
1856                .read(cx)
1857                .buffer()
1858                .read(cx)
1859                .read(cx)
1860                .anchor_before(Point::new(7, 0));
1861            editor.update(cx, |editor, cx| {
1862                let snapshot = editor.buffer().read(cx).snapshot(cx);
1863                keep_edits_in_ranges(
1864                    editor,
1865                    &snapshot,
1866                    &thread,
1867                    vec![position..position],
1868                    window,
1869                    cx,
1870                )
1871            });
1872        });
1873        cx.run_until_parked();
1874        assert_eq!(
1875            editor.read_with(cx, |editor, cx| editor.text(cx)),
1876            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1877        );
1878        assert_eq!(
1879            editor
1880                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1881                .range(),
1882            Point::new(3, 0)..Point::new(3, 0)
1883        );
1884    }
1885
1886    #[gpui::test]
1887    async fn test_singleton_agent_diff(cx: &mut TestAppContext) {
1888        cx.update(|cx| {
1889            let settings_store = SettingsStore::test(cx);
1890            cx.set_global(settings_store);
1891            language::init(cx);
1892            Project::init_settings(cx);
1893            AssistantSettings::register(cx);
1894            prompt_store::init(cx);
1895            thread_store::init(cx);
1896            workspace::init_settings(cx);
1897            ThemeSettings::register(cx);
1898            ContextServerSettings::register(cx);
1899            EditorSettings::register(cx);
1900            language_model::init_settings(cx);
1901            workspace::register_project_item::<Editor>(cx);
1902        });
1903
1904        let fs = FakeFs::new(cx.executor());
1905        fs.insert_tree(
1906            path!("/test"),
1907            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1908        )
1909        .await;
1910        fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1911            .await;
1912
1913        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1914        let buffer_path1 = project
1915            .read_with(cx, |project, cx| {
1916                project.find_project_path("test/file1", cx)
1917            })
1918            .unwrap();
1919        let buffer_path2 = project
1920            .read_with(cx, |project, cx| {
1921                project.find_project_path("test/file2", cx)
1922            })
1923            .unwrap();
1924
1925        let prompt_store = None;
1926        let thread_store = cx
1927            .update(|cx| {
1928                ThreadStore::load(
1929                    project.clone(),
1930                    cx.new(|_| ToolWorkingSet::default()),
1931                    prompt_store,
1932                    Arc::new(PromptBuilder::new(None).unwrap()),
1933                    cx,
1934                )
1935            })
1936            .await
1937            .unwrap();
1938        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1939        let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1940
1941        let (workspace, cx) =
1942            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1943
1944        // Set the active thread
1945        cx.update(|_, cx| AgentDiff::set_active_thread(&workspace.downgrade(), &thread, cx));
1946
1947        let buffer1 = project
1948            .update(cx, |project, cx| {
1949                project.open_buffer(buffer_path1.clone(), cx)
1950            })
1951            .await
1952            .unwrap();
1953        let buffer2 = project
1954            .update(cx, |project, cx| {
1955                project.open_buffer(buffer_path2.clone(), cx)
1956            })
1957            .await
1958            .unwrap();
1959
1960        // Open an editor for buffer1
1961        let editor1 = cx.new_window_entity(|window, cx| {
1962            Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
1963        });
1964
1965        workspace.update_in(cx, |workspace, window, cx| {
1966            workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
1967        });
1968        cx.run_until_parked();
1969
1970        // Make changes
1971        cx.update(|_, cx| {
1972            action_log.update(cx, |log, cx| log.track_buffer(buffer1.clone(), cx));
1973            buffer1.update(cx, |buffer, cx| {
1974                buffer
1975                    .edit(
1976                        [
1977                            (Point::new(1, 1)..Point::new(1, 2), "E"),
1978                            (Point::new(3, 2)..Point::new(3, 3), "L"),
1979                            (Point::new(5, 0)..Point::new(5, 1), "P"),
1980                            (Point::new(7, 1)..Point::new(7, 2), "W"),
1981                        ],
1982                        None,
1983                        cx,
1984                    )
1985                    .unwrap()
1986            });
1987            action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
1988
1989            action_log.update(cx, |log, cx| log.track_buffer(buffer2.clone(), cx));
1990            buffer2.update(cx, |buffer, cx| {
1991                buffer
1992                    .edit([(Point::new(2, 1)..Point::new(2, 2), "H")], None, cx)
1993                    .unwrap();
1994            });
1995            action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
1996        });
1997        cx.run_until_parked();
1998
1999        // The already opened editor displays the diff and the cursor is at the first hunk
2000        assert_eq!(
2001            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2002            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2003        );
2004        assert_eq!(
2005            editor1
2006                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2007                .range(),
2008            Point::new(1, 0)..Point::new(1, 0)
2009        );
2010
2011        // After keeping a hunk, the cursor should be positioned on the second hunk.
2012        workspace.update(cx, |_, cx| {
2013            cx.dispatch_action(&Keep);
2014        });
2015        cx.run_until_parked();
2016        assert_eq!(
2017            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2018            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2019        );
2020        assert_eq!(
2021            editor1
2022                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2023                .range(),
2024            Point::new(3, 0)..Point::new(3, 0)
2025        );
2026
2027        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
2028        editor1.update_in(cx, |editor, window, cx| {
2029            editor.change_selections(None, window, cx, |selections| {
2030                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
2031            });
2032        });
2033        workspace.update(cx, |_, cx| {
2034            cx.dispatch_action(&Reject);
2035        });
2036        cx.run_until_parked();
2037        assert_eq!(
2038            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2039            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
2040        );
2041        assert_eq!(
2042            editor1
2043                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2044                .range(),
2045            Point::new(3, 0)..Point::new(3, 0)
2046        );
2047
2048        // Keeping a range that doesn't intersect the current selection doesn't move it.
2049        editor1.update_in(cx, |editor, window, cx| {
2050            let buffer = editor.buffer().read(cx);
2051            let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2052            let snapshot = buffer.snapshot(cx);
2053            keep_edits_in_ranges(
2054                editor,
2055                &snapshot,
2056                &thread,
2057                vec![position..position],
2058                window,
2059                cx,
2060            )
2061        });
2062        cx.run_until_parked();
2063        assert_eq!(
2064            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2065            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2066        );
2067        assert_eq!(
2068            editor1
2069                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2070                .range(),
2071            Point::new(3, 0)..Point::new(3, 0)
2072        );
2073
2074        // Reviewing the last change opens the next changed buffer
2075        workspace
2076            .update_in(cx, |workspace, window, cx| {
2077                AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2078                    agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2079                })
2080            })
2081            .unwrap()
2082            .await
2083            .unwrap();
2084
2085        cx.run_until_parked();
2086
2087        let editor2 = workspace.update(cx, |workspace, cx| {
2088            workspace.active_item_as::<Editor>(cx).unwrap()
2089        });
2090
2091        let editor2_path = editor2
2092            .read_with(cx, |editor, cx| editor.project_path(cx))
2093            .unwrap();
2094        assert_eq!(editor2_path, buffer_path2);
2095
2096        assert_eq!(
2097            editor2.read_with(cx, |editor, cx| editor.text(cx)),
2098            "abc\ndef\nghi\ngHi"
2099        );
2100        assert_eq!(
2101            editor2
2102                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2103                .range(),
2104            Point::new(2, 0)..Point::new(2, 0)
2105        );
2106    }
2107}