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::ToolAuthorizationRequired
1417            | AcpThreadEvent::PromptCapabilitiesUpdated
1418            | AcpThreadEvent::AvailableCommandsUpdated(_)
1419            | AcpThreadEvent::Retry(_)
1420            | AcpThreadEvent::ModeUpdated(_)
1421            | AcpThreadEvent::ConfigOptionsUpdated(_) => {}
1422        }
1423    }
1424
1425    fn handle_workspace_event(
1426        &mut self,
1427        workspace: &Entity<Workspace>,
1428        event: &workspace::Event,
1429        window: &mut Window,
1430        cx: &mut Context<Self>,
1431    ) {
1432        if let workspace::Event::ItemAdded { item } = event
1433            && let Some(editor) = item.downcast::<Editor>()
1434            && let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx)
1435        {
1436            self.register_editor(workspace.downgrade(), buffer, editor, window, cx);
1437        }
1438    }
1439
1440    fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1441        if editor.mode().is_full() {
1442            editor
1443                .buffer()
1444                .read(cx)
1445                .as_singleton()
1446                .map(|buffer| buffer.downgrade())
1447        } else {
1448            None
1449        }
1450    }
1451
1452    fn register_editor(
1453        &mut self,
1454        workspace: WeakEntity<Workspace>,
1455        buffer: WeakEntity<Buffer>,
1456        editor: Entity<Editor>,
1457        window: &mut Window,
1458        cx: &mut Context<Self>,
1459    ) {
1460        let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1461            return;
1462        };
1463
1464        let weak_editor = editor.downgrade();
1465
1466        workspace_thread
1467            .singleton_editors
1468            .entry(buffer.clone())
1469            .or_default()
1470            .entry(weak_editor.clone())
1471            .or_insert_with(|| {
1472                let workspace = workspace.clone();
1473                cx.observe_release(&editor, move |this, _, _cx| {
1474                    let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1475                        return;
1476                    };
1477
1478                    if let Entry::Occupied(mut entry) =
1479                        active_thread.singleton_editors.entry(buffer)
1480                    {
1481                        let set = entry.get_mut();
1482                        set.remove(&weak_editor);
1483
1484                        if set.is_empty() {
1485                            entry.remove();
1486                        }
1487                    }
1488                })
1489            });
1490
1491        self.update_reviewing_editors(&workspace, window, cx);
1492    }
1493
1494    fn update_reviewing_editors(
1495        &mut self,
1496        workspace: &WeakEntity<Workspace>,
1497        window: &mut Window,
1498        cx: &mut Context<Self>,
1499    ) {
1500        if !AgentSettings::get_global(cx).single_file_review {
1501            for (editor, _) in self.reviewing_editors.drain() {
1502                editor
1503                    .update(cx, |editor, cx| {
1504                        editor.end_temporary_diff_override(cx);
1505                        editor.unregister_addon::<EditorAgentDiffAddon>();
1506                    })
1507                    .ok();
1508            }
1509            return;
1510        }
1511
1512        let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1513            return;
1514        };
1515
1516        let Some(thread) = workspace_thread.thread.upgrade() else {
1517            return;
1518        };
1519
1520        let action_log = thread.read(cx).action_log();
1521        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1522
1523        let mut unaffected = self.reviewing_editors.clone();
1524
1525        for (buffer, diff_handle) in changed_buffers {
1526            if buffer.read(cx).file().is_none() {
1527                continue;
1528            }
1529
1530            let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1531            else {
1532                continue;
1533            };
1534
1535            for weak_editor in buffer_editors.keys() {
1536                let Some(editor) = weak_editor.upgrade() else {
1537                    continue;
1538                };
1539
1540                let multibuffer = editor.read(cx).buffer().clone();
1541                multibuffer.update(cx, |multibuffer, cx| {
1542                    multibuffer.add_diff(diff_handle.clone(), cx);
1543                });
1544
1545                let reviewing_state = EditorState::Reviewing;
1546
1547                let previous_state = self
1548                    .reviewing_editors
1549                    .insert(weak_editor.clone(), reviewing_state.clone());
1550
1551                if previous_state.is_none() {
1552                    editor.update(cx, |editor, cx| {
1553                        editor.start_temporary_diff_override();
1554                        editor.set_render_diff_hunk_controls(
1555                            diff_hunk_controls(&thread, workspace.clone()),
1556                            cx,
1557                        );
1558                        editor.set_expand_all_diff_hunks(cx);
1559                        editor.register_addon(EditorAgentDiffAddon);
1560                    });
1561                } else {
1562                    unaffected.remove(weak_editor);
1563                }
1564
1565                if reviewing_state == EditorState::Reviewing
1566                    && previous_state != Some(reviewing_state)
1567                {
1568                    // Jump to first hunk when we enter review mode
1569                    editor.update(cx, |editor, cx| {
1570                        let snapshot = multibuffer.read(cx).snapshot(cx);
1571                        if let Some(first_hunk) = snapshot.diff_hunks().next() {
1572                            let first_hunk_start = first_hunk.multi_buffer_range().start;
1573
1574                            editor.change_selections(
1575                                SelectionEffects::scroll(Autoscroll::center()),
1576                                window,
1577                                cx,
1578                                |selections| {
1579                                    selections.select_ranges([first_hunk_start..first_hunk_start])
1580                                },
1581                            );
1582                        }
1583                    });
1584                }
1585            }
1586        }
1587
1588        // Remove editors from this workspace that are no longer under review
1589        for (editor, _) in unaffected {
1590            // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1591            // but that would add another lookup in `AgentDiff::editor_state`
1592            // which gets called much more frequently.
1593            let in_workspace = editor
1594                .read_with(cx, |editor, _cx| editor.workspace())
1595                .ok()
1596                .flatten()
1597                .is_some_and(|editor_workspace| {
1598                    editor_workspace.entity_id() == workspace.entity_id()
1599                });
1600
1601            if in_workspace {
1602                editor
1603                    .update(cx, |editor, cx| {
1604                        editor.end_temporary_diff_override(cx);
1605                        editor.unregister_addon::<EditorAgentDiffAddon>();
1606                    })
1607                    .ok();
1608                self.reviewing_editors.remove(&editor);
1609            }
1610        }
1611
1612        cx.notify();
1613    }
1614
1615    fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState {
1616        self.reviewing_editors
1617            .get(editor)
1618            .cloned()
1619            .unwrap_or(EditorState::Idle)
1620    }
1621
1622    fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1623        let Some(workspace) = editor.read(cx).workspace() else {
1624            return;
1625        };
1626
1627        let Some(WorkspaceThread { thread, .. }) =
1628            self.workspace_threads.get(&workspace.downgrade())
1629        else {
1630            return;
1631        };
1632
1633        let Some(thread) = thread.upgrade() else {
1634            return;
1635        };
1636
1637        AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1638    }
1639
1640    fn keep_all(
1641        editor: &Entity<Editor>,
1642        thread: &Entity<AcpThread>,
1643        _workspace: &WeakEntity<Workspace>,
1644        window: &mut Window,
1645        cx: &mut App,
1646    ) -> PostReviewState {
1647        editor.update(cx, |editor, cx| {
1648            let snapshot = editor.buffer().read(cx).snapshot(cx);
1649            keep_edits_in_ranges(
1650                editor,
1651                &snapshot,
1652                thread,
1653                vec![editor::Anchor::min()..editor::Anchor::max()],
1654                window,
1655                cx,
1656            );
1657        });
1658        PostReviewState::AllReviewed
1659    }
1660
1661    fn reject_all(
1662        editor: &Entity<Editor>,
1663        thread: &Entity<AcpThread>,
1664        workspace: &WeakEntity<Workspace>,
1665        window: &mut Window,
1666        cx: &mut App,
1667    ) -> PostReviewState {
1668        editor.update(cx, |editor, cx| {
1669            let snapshot = editor.buffer().read(cx).snapshot(cx);
1670            reject_edits_in_ranges(
1671                editor,
1672                &snapshot,
1673                thread,
1674                vec![editor::Anchor::min()..editor::Anchor::max()],
1675                workspace.clone(),
1676                window,
1677                cx,
1678            );
1679        });
1680        PostReviewState::AllReviewed
1681    }
1682
1683    fn keep(
1684        editor: &Entity<Editor>,
1685        thread: &Entity<AcpThread>,
1686        _workspace: &WeakEntity<Workspace>,
1687        window: &mut Window,
1688        cx: &mut App,
1689    ) -> PostReviewState {
1690        editor.update(cx, |editor, cx| {
1691            let snapshot = editor.buffer().read(cx).snapshot(cx);
1692            keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1693            Self::post_review_state(&snapshot)
1694        })
1695    }
1696
1697    fn reject(
1698        editor: &Entity<Editor>,
1699        thread: &Entity<AcpThread>,
1700        workspace: &WeakEntity<Workspace>,
1701        window: &mut Window,
1702        cx: &mut App,
1703    ) -> PostReviewState {
1704        editor.update(cx, |editor, cx| {
1705            let snapshot = editor.buffer().read(cx).snapshot(cx);
1706            reject_edits_in_selection(editor, &snapshot, thread, workspace.clone(), window, cx);
1707            Self::post_review_state(&snapshot)
1708        })
1709    }
1710
1711    fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1712        for (i, _) in snapshot.diff_hunks().enumerate() {
1713            if i > 0 {
1714                return PostReviewState::Pending;
1715            }
1716        }
1717        PostReviewState::AllReviewed
1718    }
1719
1720    fn review_in_active_editor(
1721        &mut self,
1722        workspace: &mut Workspace,
1723        review: impl Fn(
1724            &Entity<Editor>,
1725            &Entity<AcpThread>,
1726            &WeakEntity<Workspace>,
1727            &mut Window,
1728            &mut App,
1729        ) -> PostReviewState,
1730        window: &mut Window,
1731        cx: &mut Context<Self>,
1732    ) -> Option<Task<Result<()>>> {
1733        let active_item = workspace.active_item(cx)?;
1734        let editor = active_item.act_as::<Editor>(cx)?;
1735
1736        if !matches!(
1737            self.editor_state(&editor.downgrade()),
1738            EditorState::Reviewing
1739        ) {
1740            return None;
1741        }
1742
1743        let WorkspaceThread { thread, .. } =
1744            self.workspace_threads.get(&workspace.weak_handle())?;
1745
1746        let thread = thread.upgrade()?;
1747
1748        let review_result = review(&editor, &thread, &workspace.weak_handle(), window, cx);
1749
1750        if matches!(review_result, PostReviewState::AllReviewed)
1751            && let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton()
1752        {
1753            let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
1754
1755            let mut keys = changed_buffers.keys();
1756            keys.find(|k| *k == &curr_buffer);
1757            let next_project_path = keys
1758                .next()
1759                .filter(|k| *k != &curr_buffer)
1760                .and_then(|after| after.read(cx).project_path(cx));
1761
1762            if let Some(path) = next_project_path {
1763                let task = workspace.open_path(path, None, true, window, cx);
1764                let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1765                return Some(task);
1766            }
1767        }
1768
1769        Some(Task::ready(Ok(())))
1770    }
1771}
1772
1773enum PostReviewState {
1774    AllReviewed,
1775    Pending,
1776}
1777
1778pub struct EditorAgentDiffAddon;
1779
1780impl editor::Addon for EditorAgentDiffAddon {
1781    fn to_any(&self) -> &dyn std::any::Any {
1782        self
1783    }
1784
1785    fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1786        key_context.add("agent_diff");
1787        key_context.add("editor_agent_diff");
1788    }
1789}
1790
1791#[cfg(test)]
1792mod tests {
1793    use super::*;
1794    use crate::Keep;
1795    use acp_thread::AgentConnection as _;
1796    use agent_settings::AgentSettings;
1797    use editor::EditorSettings;
1798    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
1799    use project::{FakeFs, Project};
1800    use serde_json::json;
1801    use settings::SettingsStore;
1802    use std::{path::Path, rc::Rc};
1803    use util::path;
1804    use workspace::MultiWorkspace;
1805
1806    #[gpui::test]
1807    async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1808        cx.update(|cx| {
1809            let settings_store = SettingsStore::test(cx);
1810            cx.set_global(settings_store);
1811            prompt_store::init(cx);
1812            theme::init(theme::LoadThemes::JustBase, cx);
1813            language_model::init_settings(cx);
1814        });
1815
1816        let fs = FakeFs::new(cx.executor());
1817        fs.insert_tree(
1818            path!("/test"),
1819            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1820        )
1821        .await;
1822        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1823        let buffer_path = project
1824            .read_with(cx, |project, cx| {
1825                project.find_project_path("test/file1", cx)
1826            })
1827            .unwrap();
1828
1829        let connection = Rc::new(acp_thread::StubAgentConnection::new());
1830        let thread = cx
1831            .update(|cx| {
1832                connection
1833                    .clone()
1834                    .new_session(project.clone(), Path::new(path!("/test")), cx)
1835            })
1836            .await
1837            .unwrap();
1838
1839        let action_log = cx.read(|cx| thread.read(cx).action_log().clone());
1840
1841        let (multi_workspace, cx) =
1842            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1843        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1844        let agent_diff = cx.new_window_entity(|window, cx| {
1845            AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1846        });
1847        let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1848
1849        let buffer = project
1850            .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1851            .await
1852            .unwrap();
1853        cx.update(|_, cx| {
1854            action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
1855            buffer.update(cx, |buffer, cx| {
1856                buffer
1857                    .edit(
1858                        [
1859                            (Point::new(1, 1)..Point::new(1, 2), "E"),
1860                            (Point::new(3, 2)..Point::new(3, 3), "L"),
1861                            (Point::new(5, 0)..Point::new(5, 1), "P"),
1862                            (Point::new(7, 1)..Point::new(7, 2), "W"),
1863                        ],
1864                        None,
1865                        cx,
1866                    )
1867                    .unwrap()
1868            });
1869            action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1870        });
1871        cx.run_until_parked();
1872
1873        // When opening the assistant diff, the cursor is positioned on the first hunk.
1874        assert_eq!(
1875            editor.read_with(cx, |editor, cx| editor.text(cx)),
1876            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1877        );
1878        assert_eq!(
1879            editor
1880                .update(cx, |editor, cx| editor
1881                    .selections
1882                    .newest::<Point>(&editor.display_snapshot(cx)))
1883                .range(),
1884            Point::new(1, 0)..Point::new(1, 0)
1885        );
1886
1887        // After keeping a hunk, the cursor should be positioned on the second hunk.
1888        agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1889        cx.run_until_parked();
1890        assert_eq!(
1891            editor.read_with(cx, |editor, cx| editor.text(cx)),
1892            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1893        );
1894        assert_eq!(
1895            editor
1896                .update(cx, |editor, cx| editor
1897                    .selections
1898                    .newest::<Point>(&editor.display_snapshot(cx)))
1899                .range(),
1900            Point::new(3, 0)..Point::new(3, 0)
1901        );
1902
1903        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1904        editor.update_in(cx, |editor, window, cx| {
1905            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1906                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1907            });
1908        });
1909        agent_diff.update_in(cx, |diff, window, cx| {
1910            diff.reject(&crate::Reject, window, cx)
1911        });
1912        cx.run_until_parked();
1913        assert_eq!(
1914            editor.read_with(cx, |editor, cx| editor.text(cx)),
1915            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1916        );
1917        assert_eq!(
1918            editor
1919                .update(cx, |editor, cx| editor
1920                    .selections
1921                    .newest::<Point>(&editor.display_snapshot(cx)))
1922                .range(),
1923            Point::new(3, 0)..Point::new(3, 0)
1924        );
1925
1926        // Keeping a range that doesn't intersect the current selection doesn't move it.
1927        agent_diff.update_in(cx, |_diff, window, cx| {
1928            let position = editor
1929                .read(cx)
1930                .buffer()
1931                .read(cx)
1932                .read(cx)
1933                .anchor_before(Point::new(7, 0));
1934            editor.update(cx, |editor, cx| {
1935                let snapshot = editor.buffer().read(cx).snapshot(cx);
1936                keep_edits_in_ranges(
1937                    editor,
1938                    &snapshot,
1939                    &thread,
1940                    vec![position..position],
1941                    window,
1942                    cx,
1943                )
1944            });
1945        });
1946        cx.run_until_parked();
1947        assert_eq!(
1948            editor.read_with(cx, |editor, cx| editor.text(cx)),
1949            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1950        );
1951        assert_eq!(
1952            editor
1953                .update(cx, |editor, cx| editor
1954                    .selections
1955                    .newest::<Point>(&editor.display_snapshot(cx)))
1956                .range(),
1957            Point::new(3, 0)..Point::new(3, 0)
1958        );
1959    }
1960
1961    #[gpui::test]
1962    async fn test_single_file_review_diff(cx: &mut TestAppContext) {
1963        cx.update(|cx| {
1964            let settings_store = SettingsStore::test(cx);
1965            cx.set_global(settings_store);
1966            prompt_store::init(cx);
1967            theme::init(theme::LoadThemes::JustBase, cx);
1968            language_model::init_settings(cx);
1969            workspace::register_project_item::<Editor>(cx);
1970        });
1971
1972        cx.update(|cx| {
1973            SettingsStore::update_global(cx, |store, _cx| {
1974                let mut agent_settings = store.get::<AgentSettings>(None).clone();
1975                agent_settings.single_file_review = true;
1976                store.override_global(agent_settings);
1977            });
1978        });
1979
1980        let fs = FakeFs::new(cx.executor());
1981        fs.insert_tree(
1982            path!("/test"),
1983            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1984        )
1985        .await;
1986        fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1987            .await;
1988
1989        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1990        let buffer_path1 = project
1991            .read_with(cx, |project, cx| {
1992                project.find_project_path("test/file1", cx)
1993            })
1994            .unwrap();
1995        let buffer_path2 = project
1996            .read_with(cx, |project, cx| {
1997                project.find_project_path("test/file2", cx)
1998            })
1999            .unwrap();
2000
2001        let (multi_workspace, cx) =
2002            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2003        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2004
2005        // Add the diff toolbar to the active pane
2006        let diff_toolbar = cx.new_window_entity(|_, cx| AgentDiffToolbar::new(cx));
2007
2008        workspace.update_in(cx, {
2009            let diff_toolbar = diff_toolbar.clone();
2010
2011            move |workspace, window, cx| {
2012                workspace.active_pane().update(cx, |pane, cx| {
2013                    pane.toolbar().update(cx, |toolbar, cx| {
2014                        toolbar.add_item(diff_toolbar, window, cx);
2015                    });
2016                })
2017            }
2018        });
2019
2020        let connection = Rc::new(acp_thread::StubAgentConnection::new());
2021        let thread = cx
2022            .update(|_, cx| {
2023                connection
2024                    .clone()
2025                    .new_session(project.clone(), Path::new(path!("/test")), cx)
2026            })
2027            .await
2028            .unwrap();
2029        let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
2030
2031        // Set the active thread
2032        cx.update(|window, cx| {
2033            AgentDiff::set_active_thread(&workspace.downgrade(), thread.clone(), window, cx)
2034        });
2035
2036        let buffer1 = project
2037            .update(cx, |project, cx| {
2038                project.open_buffer(buffer_path1.clone(), cx)
2039            })
2040            .await
2041            .unwrap();
2042        let buffer2 = project
2043            .update(cx, |project, cx| {
2044                project.open_buffer(buffer_path2.clone(), cx)
2045            })
2046            .await
2047            .unwrap();
2048
2049        // Open an editor for buffer1
2050        let editor1 = cx.new_window_entity(|window, cx| {
2051            Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
2052        });
2053
2054        workspace.update_in(cx, |workspace, window, cx| {
2055            workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
2056        });
2057        cx.run_until_parked();
2058
2059        // Toolbar knows about the current editor, but it's hidden since there are no changes yet
2060        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2061            toolbar.active_item,
2062            Some(AgentDiffToolbarItem::Editor {
2063                state: EditorState::Idle,
2064                ..
2065            })
2066        )));
2067        assert_eq!(
2068            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2069            ToolbarItemLocation::Hidden
2070        );
2071
2072        // Make changes
2073        cx.update(|_, cx| {
2074            action_log.update(cx, |log, cx| log.buffer_read(buffer1.clone(), cx));
2075            buffer1.update(cx, |buffer, cx| {
2076                buffer
2077                    .edit(
2078                        [
2079                            (Point::new(1, 1)..Point::new(1, 2), "E"),
2080                            (Point::new(3, 2)..Point::new(3, 3), "L"),
2081                            (Point::new(5, 0)..Point::new(5, 1), "P"),
2082                            (Point::new(7, 1)..Point::new(7, 2), "W"),
2083                        ],
2084                        None,
2085                        cx,
2086                    )
2087                    .unwrap()
2088            });
2089            action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
2090
2091            action_log.update(cx, |log, cx| log.buffer_read(buffer2.clone(), cx));
2092            buffer2.update(cx, |buffer, cx| {
2093                buffer
2094                    .edit(
2095                        [
2096                            (Point::new(0, 0)..Point::new(0, 1), "A"),
2097                            (Point::new(2, 1)..Point::new(2, 2), "H"),
2098                        ],
2099                        None,
2100                        cx,
2101                    )
2102                    .unwrap();
2103            });
2104            action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
2105        });
2106        cx.run_until_parked();
2107
2108        // The already opened editor displays the diff and the cursor is at the first hunk
2109        assert_eq!(
2110            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2111            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2112        );
2113        assert_eq!(
2114            editor1
2115                .update(cx, |editor, cx| editor
2116                    .selections
2117                    .newest::<Point>(&editor.display_snapshot(cx)))
2118                .range(),
2119            Point::new(1, 0)..Point::new(1, 0)
2120        );
2121
2122        // The toolbar is displayed in the right state
2123        assert_eq!(
2124            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2125            ToolbarItemLocation::PrimaryRight
2126        );
2127        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2128            toolbar.active_item,
2129            Some(AgentDiffToolbarItem::Editor {
2130                state: EditorState::Reviewing,
2131                ..
2132            })
2133        )));
2134
2135        // The toolbar respects its setting
2136        override_toolbar_agent_review_setting(false, cx);
2137        assert_eq!(
2138            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2139            ToolbarItemLocation::Hidden
2140        );
2141        override_toolbar_agent_review_setting(true, cx);
2142        assert_eq!(
2143            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2144            ToolbarItemLocation::PrimaryRight
2145        );
2146
2147        // After keeping a hunk, the cursor should be positioned on the second hunk.
2148        workspace.update(cx, |_, cx| {
2149            cx.dispatch_action(&Keep);
2150        });
2151        cx.run_until_parked();
2152        assert_eq!(
2153            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2154            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2155        );
2156        assert_eq!(
2157            editor1
2158                .update(cx, |editor, cx| editor
2159                    .selections
2160                    .newest::<Point>(&editor.display_snapshot(cx)))
2161                .range(),
2162            Point::new(3, 0)..Point::new(3, 0)
2163        );
2164
2165        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
2166        editor1.update_in(cx, |editor, window, cx| {
2167            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
2168                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
2169            });
2170        });
2171        workspace.update(cx, |_, cx| {
2172            cx.dispatch_action(&Reject);
2173        });
2174        cx.run_until_parked();
2175        assert_eq!(
2176            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2177            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
2178        );
2179        assert_eq!(
2180            editor1
2181                .update(cx, |editor, cx| editor
2182                    .selections
2183                    .newest::<Point>(&editor.display_snapshot(cx)))
2184                .range(),
2185            Point::new(3, 0)..Point::new(3, 0)
2186        );
2187
2188        // Keeping a range that doesn't intersect the current selection doesn't move it.
2189        editor1.update_in(cx, |editor, window, cx| {
2190            let buffer = editor.buffer().read(cx);
2191            let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2192            let snapshot = buffer.snapshot(cx);
2193            keep_edits_in_ranges(
2194                editor,
2195                &snapshot,
2196                &thread,
2197                vec![position..position],
2198                window,
2199                cx,
2200            )
2201        });
2202        cx.run_until_parked();
2203        assert_eq!(
2204            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2205            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2206        );
2207        assert_eq!(
2208            editor1
2209                .update(cx, |editor, cx| editor
2210                    .selections
2211                    .newest::<Point>(&editor.display_snapshot(cx)))
2212                .range(),
2213            Point::new(3, 0)..Point::new(3, 0)
2214        );
2215
2216        // Reviewing the last change opens the next changed buffer
2217        workspace
2218            .update_in(cx, |workspace, window, cx| {
2219                AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2220                    agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2221                })
2222            })
2223            .unwrap()
2224            .await
2225            .unwrap();
2226
2227        cx.run_until_parked();
2228
2229        let editor2 = workspace.update(cx, |workspace, cx| {
2230            workspace.active_item_as::<Editor>(cx).unwrap()
2231        });
2232
2233        let editor2_path = editor2
2234            .read_with(cx, |editor, cx| editor.project_path(cx))
2235            .unwrap();
2236        assert_eq!(editor2_path, buffer_path2);
2237
2238        assert_eq!(
2239            editor2.read_with(cx, |editor, cx| editor.text(cx)),
2240            "abc\nAbc\ndef\nghi\ngHi"
2241        );
2242        assert_eq!(
2243            editor2
2244                .update(cx, |editor, cx| editor
2245                    .selections
2246                    .newest::<Point>(&editor.display_snapshot(cx)))
2247                .range(),
2248            Point::new(0, 0)..Point::new(0, 0)
2249        );
2250
2251        // Editor 1 toolbar is hidden since all changes have been reviewed
2252        workspace.update_in(cx, |workspace, window, cx| {
2253            workspace.activate_item(&editor1, true, true, window, cx)
2254        });
2255
2256        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2257            toolbar.active_item,
2258            Some(AgentDiffToolbarItem::Editor {
2259                state: EditorState::Idle,
2260                ..
2261            })
2262        )));
2263        assert_eq!(
2264            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2265            ToolbarItemLocation::Hidden
2266        );
2267    }
2268
2269    fn override_toolbar_agent_review_setting(active: bool, cx: &mut VisualTestContext) {
2270        cx.update(|_window, cx| {
2271            SettingsStore::update_global(cx, |store, _cx| {
2272                let mut editor_settings = store.get::<EditorSettings>(None).clone();
2273                editor_settings.toolbar.agent_review = active;
2274                store.override_global(editor_settings);
2275            })
2276        });
2277        cx.run_until_parked();
2278    }
2279}