agent_diff.rs

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