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                                        true,
 835                                        window,
 836                                        cx,
 837                                    );
 838                                    editor.expand_selected_diff_hunks(cx);
 839                                });
 840                            }
 841                        }),
 842                )
 843                .child(
 844                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
 845                        .shape(IconButtonShape::Square)
 846                        .icon_size(IconSize::Small)
 847                        // .disabled(!has_multiple_hunks)
 848                        .tooltip({
 849                            let focus_handle = editor.focus_handle(cx);
 850                            move |_window, cx| {
 851                                Tooltip::for_action_in(
 852                                    "Previous Hunk",
 853                                    &GoToPreviousHunk,
 854                                    &focus_handle,
 855                                    cx,
 856                                )
 857                            }
 858                        })
 859                        .on_click({
 860                            let editor = editor.clone();
 861                            move |_event, window, cx| {
 862                                editor.update(cx, |editor, cx| {
 863                                    let snapshot = editor.snapshot(window, cx);
 864                                    let point =
 865                                        hunk_range.start.to_point(&snapshot.buffer_snapshot());
 866                                    editor.go_to_hunk_before_or_after_position(
 867                                        &snapshot,
 868                                        point,
 869                                        Direction::Prev,
 870                                        true,
 871                                        window,
 872                                        cx,
 873                                    );
 874                                    editor.expand_selected_diff_hunks(cx);
 875                                });
 876                            }
 877                        }),
 878                )
 879            },
 880        )
 881        .into_any_element()
 882}
 883
 884struct AgentDiffAddon;
 885
 886impl editor::Addon for AgentDiffAddon {
 887    fn to_any(&self) -> &dyn std::any::Any {
 888        self
 889    }
 890
 891    fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
 892        key_context.add("agent_diff");
 893    }
 894}
 895
 896pub struct AgentDiffToolbar {
 897    active_item: Option<AgentDiffToolbarItem>,
 898    _settings_subscription: Subscription,
 899}
 900
 901pub enum AgentDiffToolbarItem {
 902    Pane(WeakEntity<AgentDiffPane>),
 903    Editor {
 904        editor: WeakEntity<Editor>,
 905        state: EditorState,
 906        _diff_subscription: Subscription,
 907    },
 908}
 909
 910impl AgentDiffToolbar {
 911    pub fn new(cx: &mut Context<Self>) -> Self {
 912        Self {
 913            active_item: None,
 914            _settings_subscription: cx.observe_global::<SettingsStore>(Self::update_location),
 915        }
 916    }
 917
 918    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 919        let Some(active_item) = self.active_item.as_ref() else {
 920            return;
 921        };
 922
 923        match active_item {
 924            AgentDiffToolbarItem::Pane(agent_diff) => {
 925                if let Some(agent_diff) = agent_diff.upgrade() {
 926                    agent_diff.focus_handle(cx).focus(window, cx);
 927                }
 928            }
 929            AgentDiffToolbarItem::Editor { editor, .. } => {
 930                if let Some(editor) = editor.upgrade() {
 931                    editor.read(cx).focus_handle(cx).focus(window, cx);
 932                }
 933            }
 934        }
 935
 936        let action = action.boxed_clone();
 937        cx.defer(move |cx| {
 938            cx.dispatch_action(action.as_ref());
 939        })
 940    }
 941
 942    fn handle_diff_notify(&mut self, agent_diff: Entity<AgentDiff>, cx: &mut Context<Self>) {
 943        let Some(AgentDiffToolbarItem::Editor { editor, state, .. }) = self.active_item.as_mut()
 944        else {
 945            return;
 946        };
 947
 948        *state = agent_diff.read(cx).editor_state(editor);
 949        self.update_location(cx);
 950        cx.notify();
 951    }
 952
 953    fn update_location(&mut self, cx: &mut Context<Self>) {
 954        let location = self.location(cx);
 955        cx.emit(ToolbarItemEvent::ChangeLocation(location));
 956    }
 957
 958    fn location(&self, cx: &App) -> ToolbarItemLocation {
 959        if !EditorSettings::get_global(cx).toolbar.agent_review {
 960            return ToolbarItemLocation::Hidden;
 961        }
 962
 963        match &self.active_item {
 964            None => ToolbarItemLocation::Hidden,
 965            Some(AgentDiffToolbarItem::Pane(_)) => ToolbarItemLocation::PrimaryRight,
 966            Some(AgentDiffToolbarItem::Editor { state, .. }) => match state {
 967                EditorState::Reviewing => ToolbarItemLocation::PrimaryRight,
 968                EditorState::Idle => ToolbarItemLocation::Hidden,
 969            },
 970        }
 971    }
 972}
 973
 974impl EventEmitter<ToolbarItemEvent> for AgentDiffToolbar {}
 975
 976impl ToolbarItemView for AgentDiffToolbar {
 977    fn set_active_pane_item(
 978        &mut self,
 979        active_pane_item: Option<&dyn ItemHandle>,
 980        _: &mut Window,
 981        cx: &mut Context<Self>,
 982    ) -> ToolbarItemLocation {
 983        if let Some(item) = active_pane_item {
 984            if let Some(pane) = item.act_as::<AgentDiffPane>(cx) {
 985                self.active_item = Some(AgentDiffToolbarItem::Pane(pane.downgrade()));
 986                return self.location(cx);
 987            }
 988
 989            if let Some(editor) = item.act_as::<Editor>(cx)
 990                && editor.read(cx).mode().is_full()
 991            {
 992                let agent_diff = AgentDiff::global(cx);
 993
 994                self.active_item = Some(AgentDiffToolbarItem::Editor {
 995                    editor: editor.downgrade(),
 996                    state: agent_diff.read(cx).editor_state(&editor.downgrade()),
 997                    _diff_subscription: cx.observe(&agent_diff, Self::handle_diff_notify),
 998                });
 999
1000                return self.location(cx);
1001            }
1002        }
1003
1004        self.active_item = None;
1005        self.location(cx)
1006    }
1007
1008    fn pane_focus_update(
1009        &mut self,
1010        _pane_focused: bool,
1011        _window: &mut Window,
1012        _cx: &mut Context<Self>,
1013    ) {
1014    }
1015}
1016
1017impl Render for AgentDiffToolbar {
1018    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1019        let spinner_icon = div()
1020            .px_0p5()
1021            .id("generating")
1022            .tooltip(Tooltip::text("Generating Changes…"))
1023            .child(
1024                Icon::new(IconName::LoadCircle)
1025                    .size(IconSize::Small)
1026                    .color(Color::Accent)
1027                    .with_rotate_animation(3),
1028            )
1029            .into_any();
1030
1031        let Some(active_item) = self.active_item.as_ref() else {
1032            return Empty.into_any();
1033        };
1034
1035        match active_item {
1036            AgentDiffToolbarItem::Editor { editor, state, .. } => {
1037                let Some(editor) = editor.upgrade() else {
1038                    return Empty.into_any();
1039                };
1040
1041                let editor_focus_handle = editor.read(cx).focus_handle(cx);
1042
1043                let content = match state {
1044                    EditorState::Idle => return Empty.into_any(),
1045                    EditorState::Reviewing => vec![
1046                        h_flex()
1047                            .child(
1048                                IconButton::new("hunk-up", IconName::ArrowUp)
1049                                    .icon_size(IconSize::Small)
1050                                    .tooltip(Tooltip::for_action_title_in(
1051                                        "Previous Hunk",
1052                                        &GoToPreviousHunk,
1053                                        &editor_focus_handle,
1054                                    ))
1055                                    .on_click({
1056                                        let editor_focus_handle = editor_focus_handle.clone();
1057                                        move |_, window, cx| {
1058                                            editor_focus_handle.dispatch_action(
1059                                                &GoToPreviousHunk,
1060                                                window,
1061                                                cx,
1062                                            );
1063                                        }
1064                                    }),
1065                            )
1066                            .child(
1067                                IconButton::new("hunk-down", IconName::ArrowDown)
1068                                    .icon_size(IconSize::Small)
1069                                    .tooltip(Tooltip::for_action_title_in(
1070                                        "Next Hunk",
1071                                        &GoToHunk,
1072                                        &editor_focus_handle,
1073                                    ))
1074                                    .on_click({
1075                                        let editor_focus_handle = editor_focus_handle.clone();
1076                                        move |_, window, cx| {
1077                                            editor_focus_handle
1078                                                .dispatch_action(&GoToHunk, window, cx);
1079                                        }
1080                                    }),
1081                            )
1082                            .into_any_element(),
1083                        vertical_divider().into_any_element(),
1084                        h_flex()
1085                            .gap_0p5()
1086                            .child(
1087                                Button::new("reject-all", "Reject All")
1088                                    .key_binding({
1089                                        KeyBinding::for_action_in(
1090                                            &RejectAll,
1091                                            &editor_focus_handle,
1092                                            cx,
1093                                        )
1094                                        .map(|kb| kb.size(rems_from_px(12.)))
1095                                    })
1096                                    .on_click(cx.listener(|this, _, window, cx| {
1097                                        this.dispatch_action(&RejectAll, window, cx)
1098                                    })),
1099                            )
1100                            .child(
1101                                Button::new("keep-all", "Keep All")
1102                                    .key_binding({
1103                                        KeyBinding::for_action_in(
1104                                            &KeepAll,
1105                                            &editor_focus_handle,
1106                                            cx,
1107                                        )
1108                                        .map(|kb| kb.size(rems_from_px(12.)))
1109                                    })
1110                                    .on_click(cx.listener(|this, _, window, cx| {
1111                                        this.dispatch_action(&KeepAll, window, cx)
1112                                    })),
1113                            )
1114                            .into_any_element(),
1115                    ],
1116                };
1117
1118                h_flex()
1119                    .track_focus(&editor_focus_handle)
1120                    .size_full()
1121                    .px_1()
1122                    .mr_1()
1123                    .gap_1()
1124                    .children(content)
1125                    .child(vertical_divider())
1126                    .when_some(editor.read(cx).workspace(), |this, _workspace| {
1127                        this.child(
1128                            IconButton::new("review", IconName::ListTodo)
1129                                .icon_size(IconSize::Small)
1130                                .tooltip(Tooltip::for_action_title_in(
1131                                    "Review All Files",
1132                                    &OpenAgentDiff,
1133                                    &editor_focus_handle,
1134                                ))
1135                                .on_click({
1136                                    cx.listener(move |this, _, window, cx| {
1137                                        this.dispatch_action(&OpenAgentDiff, window, cx);
1138                                    })
1139                                }),
1140                        )
1141                    })
1142                    .child(vertical_divider())
1143                    .on_action({
1144                        let editor = editor.clone();
1145                        move |_action: &OpenAgentDiff, window, cx| {
1146                            AgentDiff::global(cx).update(cx, |agent_diff, cx| {
1147                                agent_diff.deploy_pane_from_editor(&editor, window, cx);
1148                            });
1149                        }
1150                    })
1151                    .into_any()
1152            }
1153            AgentDiffToolbarItem::Pane(agent_diff) => {
1154                let Some(agent_diff) = agent_diff.upgrade() else {
1155                    return Empty.into_any();
1156                };
1157
1158                let has_pending_edit_tool_use = agent_diff
1159                    .read(cx)
1160                    .thread
1161                    .read(cx)
1162                    .has_pending_edit_tool_calls();
1163
1164                if has_pending_edit_tool_use {
1165                    return div().px_2().child(spinner_icon).into_any();
1166                }
1167
1168                let is_empty = agent_diff.read(cx).multibuffer.read(cx).is_empty();
1169                if is_empty {
1170                    return Empty.into_any();
1171                }
1172
1173                let focus_handle = agent_diff.focus_handle(cx);
1174
1175                h_group_xl()
1176                    .my_neg_1()
1177                    .py_1()
1178                    .items_center()
1179                    .flex_wrap()
1180                    .child(
1181                        h_group_sm()
1182                            .child(
1183                                Button::new("reject-all", "Reject All")
1184                                    .key_binding({
1185                                        KeyBinding::for_action_in(&RejectAll, &focus_handle, cx)
1186                                            .map(|kb| kb.size(rems_from_px(12.)))
1187                                    })
1188                                    .on_click(cx.listener(|this, _, window, cx| {
1189                                        this.dispatch_action(&RejectAll, window, cx)
1190                                    })),
1191                            )
1192                            .child(
1193                                Button::new("keep-all", "Keep All")
1194                                    .key_binding({
1195                                        KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
1196                                            .map(|kb| kb.size(rems_from_px(12.)))
1197                                    })
1198                                    .on_click(cx.listener(|this, _, window, cx| {
1199                                        this.dispatch_action(&KeepAll, window, cx)
1200                                    })),
1201                            ),
1202                    )
1203                    .into_any()
1204            }
1205        }
1206    }
1207}
1208
1209#[derive(Default)]
1210pub struct AgentDiff {
1211    reviewing_editors: HashMap<WeakEntity<Editor>, EditorState>,
1212    workspace_threads: HashMap<WeakEntity<Workspace>, WorkspaceThread>,
1213}
1214
1215#[derive(Clone, Debug, PartialEq, Eq)]
1216pub enum EditorState {
1217    Idle,
1218    Reviewing,
1219}
1220
1221struct WorkspaceThread {
1222    thread: WeakEntity<AcpThread>,
1223    _thread_subscriptions: (Subscription, Subscription),
1224    singleton_editors: HashMap<WeakEntity<Buffer>, HashMap<WeakEntity<Editor>, Subscription>>,
1225    _settings_subscription: Subscription,
1226    _workspace_subscription: Option<Subscription>,
1227}
1228
1229struct AgentDiffGlobal(Entity<AgentDiff>);
1230
1231impl Global for AgentDiffGlobal {}
1232
1233impl AgentDiff {
1234    fn global(cx: &mut App) -> Entity<Self> {
1235        cx.try_global::<AgentDiffGlobal>()
1236            .map(|global| global.0.clone())
1237            .unwrap_or_else(|| {
1238                let entity = cx.new(|_cx| Self::default());
1239                let global = AgentDiffGlobal(entity.clone());
1240                cx.set_global(global);
1241                entity
1242            })
1243    }
1244
1245    pub fn set_active_thread(
1246        workspace: &WeakEntity<Workspace>,
1247        thread: Entity<AcpThread>,
1248        window: &mut Window,
1249        cx: &mut App,
1250    ) {
1251        Self::global(cx).update(cx, |this, cx| {
1252            this.register_active_thread_impl(workspace, thread, window, cx);
1253        });
1254    }
1255
1256    fn register_active_thread_impl(
1257        &mut self,
1258        workspace: &WeakEntity<Workspace>,
1259        thread: Entity<AcpThread>,
1260        window: &mut Window,
1261        cx: &mut Context<Self>,
1262    ) {
1263        let action_log = thread.read(cx).action_log().clone();
1264
1265        let action_log_subscription = cx.observe_in(&action_log, window, {
1266            let workspace = workspace.clone();
1267            move |this, _action_log, window, cx| {
1268                this.update_reviewing_editors(&workspace, window, cx);
1269            }
1270        });
1271
1272        let thread_subscription = cx.subscribe_in(&thread, window, {
1273            let workspace = workspace.clone();
1274            move |this, thread, event, window, cx| {
1275                this.handle_acp_thread_event(&workspace, thread, event, window, cx)
1276            }
1277        });
1278
1279        if let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) {
1280            // replace thread and action log subscription, but keep editors
1281            workspace_thread.thread = thread.downgrade();
1282            workspace_thread._thread_subscriptions = (action_log_subscription, thread_subscription);
1283            self.update_reviewing_editors(workspace, window, cx);
1284            return;
1285        }
1286
1287        let settings_subscription = cx.observe_global_in::<SettingsStore>(window, {
1288            let workspace = workspace.clone();
1289            let mut was_active = AgentSettings::get_global(cx).single_file_review;
1290            move |this, window, cx| {
1291                let is_active = AgentSettings::get_global(cx).single_file_review;
1292                if was_active != is_active {
1293                    was_active = is_active;
1294                    this.update_reviewing_editors(&workspace, window, cx);
1295                }
1296            }
1297        });
1298
1299        let workspace_subscription = workspace
1300            .upgrade()
1301            .map(|workspace| cx.subscribe_in(&workspace, window, Self::handle_workspace_event));
1302
1303        self.workspace_threads.insert(
1304            workspace.clone(),
1305            WorkspaceThread {
1306                thread: thread.downgrade(),
1307                _thread_subscriptions: (action_log_subscription, thread_subscription),
1308                singleton_editors: HashMap::default(),
1309                _settings_subscription: settings_subscription,
1310                _workspace_subscription: workspace_subscription,
1311            },
1312        );
1313
1314        let workspace = workspace.clone();
1315        cx.defer_in(window, move |this, window, cx| {
1316            if let Some(workspace) = workspace.upgrade() {
1317                this.register_workspace(workspace, window, cx);
1318            }
1319        });
1320    }
1321
1322    fn register_workspace(
1323        &mut self,
1324        workspace: Entity<Workspace>,
1325        window: &mut Window,
1326        cx: &mut Context<Self>,
1327    ) {
1328        let agent_diff = cx.entity();
1329
1330        let editors = workspace.update(cx, |workspace, cx| {
1331            let agent_diff = agent_diff.clone();
1332
1333            Self::register_review_action::<Keep>(workspace, Self::keep, &agent_diff);
1334            Self::register_review_action::<Reject>(workspace, Self::reject, &agent_diff);
1335            Self::register_review_action::<KeepAll>(workspace, Self::keep_all, &agent_diff);
1336            Self::register_review_action::<RejectAll>(workspace, Self::reject_all, &agent_diff);
1337
1338            workspace.items_of_type(cx).collect::<Vec<_>>()
1339        });
1340
1341        let weak_workspace = workspace.downgrade();
1342
1343        for editor in editors {
1344            if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1345                self.register_editor(weak_workspace.clone(), buffer, editor, window, cx);
1346            };
1347        }
1348
1349        self.update_reviewing_editors(&weak_workspace, window, cx);
1350    }
1351
1352    fn register_review_action<T: Action>(
1353        workspace: &mut Workspace,
1354        review: impl Fn(
1355            &Entity<Editor>,
1356            &Entity<AcpThread>,
1357            &WeakEntity<Workspace>,
1358            &mut Window,
1359            &mut App,
1360        ) -> PostReviewState
1361        + 'static,
1362        this: &Entity<AgentDiff>,
1363    ) {
1364        let this = this.clone();
1365        workspace.register_action(move |workspace, _: &T, window, cx| {
1366            let review = &review;
1367            let task = this.update(cx, |this, cx| {
1368                this.review_in_active_editor(workspace, review, window, cx)
1369            });
1370
1371            if let Some(task) = task {
1372                task.detach_and_log_err(cx);
1373            } else {
1374                cx.propagate();
1375            }
1376        });
1377    }
1378
1379    fn handle_acp_thread_event(
1380        &mut self,
1381        workspace: &WeakEntity<Workspace>,
1382        thread: &Entity<AcpThread>,
1383        event: &AcpThreadEvent,
1384        window: &mut Window,
1385        cx: &mut Context<Self>,
1386    ) {
1387        match event {
1388            AcpThreadEvent::NewEntry => {
1389                if thread
1390                    .read(cx)
1391                    .entries()
1392                    .last()
1393                    .is_some_and(|entry| entry.diffs().next().is_some())
1394                {
1395                    self.update_reviewing_editors(workspace, window, cx);
1396                }
1397            }
1398            AcpThreadEvent::EntryUpdated(ix) => {
1399                if thread
1400                    .read(cx)
1401                    .entries()
1402                    .get(*ix)
1403                    .is_some_and(|entry| entry.diffs().next().is_some())
1404                {
1405                    self.update_reviewing_editors(workspace, window, cx);
1406                }
1407            }
1408            AcpThreadEvent::Stopped(_) => {
1409                self.update_reviewing_editors(workspace, window, cx);
1410            }
1411            AcpThreadEvent::Error | AcpThreadEvent::LoadError(_) | AcpThreadEvent::Refusal => {
1412                self.update_reviewing_editors(workspace, window, cx);
1413            }
1414            AcpThreadEvent::TitleUpdated
1415            | AcpThreadEvent::TokenUsageUpdated
1416            | AcpThreadEvent::SubagentSpawned(_)
1417            | AcpThreadEvent::EntriesRemoved(_)
1418            | AcpThreadEvent::ToolAuthorizationRequested(_)
1419            | AcpThreadEvent::ToolAuthorizationReceived(_)
1420            | AcpThreadEvent::PromptCapabilitiesUpdated
1421            | AcpThreadEvent::AvailableCommandsUpdated(_)
1422            | AcpThreadEvent::Retry(_)
1423            | AcpThreadEvent::ModeUpdated(_)
1424            | AcpThreadEvent::ConfigOptionsUpdated(_) => {}
1425        }
1426    }
1427
1428    fn handle_workspace_event(
1429        &mut self,
1430        workspace: &Entity<Workspace>,
1431        event: &workspace::Event,
1432        window: &mut Window,
1433        cx: &mut Context<Self>,
1434    ) {
1435        if let workspace::Event::ItemAdded { item } = event
1436            && let Some(editor) = item.downcast::<Editor>()
1437            && let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx)
1438        {
1439            self.register_editor(workspace.downgrade(), buffer, editor, window, cx);
1440        }
1441    }
1442
1443    fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1444        if editor.mode().is_full() {
1445            editor
1446                .buffer()
1447                .read(cx)
1448                .as_singleton()
1449                .map(|buffer| buffer.downgrade())
1450        } else {
1451            None
1452        }
1453    }
1454
1455    fn register_editor(
1456        &mut self,
1457        workspace: WeakEntity<Workspace>,
1458        buffer: WeakEntity<Buffer>,
1459        editor: Entity<Editor>,
1460        window: &mut Window,
1461        cx: &mut Context<Self>,
1462    ) {
1463        let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1464            return;
1465        };
1466
1467        let weak_editor = editor.downgrade();
1468
1469        workspace_thread
1470            .singleton_editors
1471            .entry(buffer.clone())
1472            .or_default()
1473            .entry(weak_editor.clone())
1474            .or_insert_with(|| {
1475                let workspace = workspace.clone();
1476                cx.observe_release(&editor, move |this, _, _cx| {
1477                    let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1478                        return;
1479                    };
1480
1481                    if let Entry::Occupied(mut entry) =
1482                        active_thread.singleton_editors.entry(buffer)
1483                    {
1484                        let set = entry.get_mut();
1485                        set.remove(&weak_editor);
1486
1487                        if set.is_empty() {
1488                            entry.remove();
1489                        }
1490                    }
1491                })
1492            });
1493
1494        self.update_reviewing_editors(&workspace, window, cx);
1495    }
1496
1497    fn update_reviewing_editors(
1498        &mut self,
1499        workspace: &WeakEntity<Workspace>,
1500        window: &mut Window,
1501        cx: &mut Context<Self>,
1502    ) {
1503        if !AgentSettings::get_global(cx).single_file_review {
1504            for (editor, _) in self.reviewing_editors.drain() {
1505                editor
1506                    .update(cx, |editor, cx| {
1507                        editor.end_temporary_diff_override(cx);
1508                        editor.unregister_addon::<EditorAgentDiffAddon>();
1509                    })
1510                    .ok();
1511            }
1512            return;
1513        }
1514
1515        let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1516            return;
1517        };
1518
1519        let Some(thread) = workspace_thread.thread.upgrade() else {
1520            return;
1521        };
1522
1523        let action_log = thread.read(cx).action_log();
1524        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1525
1526        let mut unaffected = self.reviewing_editors.clone();
1527
1528        for (buffer, diff_handle) in changed_buffers {
1529            if buffer.read(cx).file().is_none() {
1530                continue;
1531            }
1532
1533            let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1534            else {
1535                continue;
1536            };
1537
1538            for weak_editor in buffer_editors.keys() {
1539                let Some(editor) = weak_editor.upgrade() else {
1540                    continue;
1541                };
1542
1543                let multibuffer = editor.read(cx).buffer().clone();
1544                multibuffer.update(cx, |multibuffer, cx| {
1545                    multibuffer.add_diff(diff_handle.clone(), cx);
1546                });
1547
1548                let reviewing_state = EditorState::Reviewing;
1549
1550                let previous_state = self
1551                    .reviewing_editors
1552                    .insert(weak_editor.clone(), reviewing_state.clone());
1553
1554                if previous_state.is_none() {
1555                    editor.update(cx, |editor, cx| {
1556                        editor.start_temporary_diff_override();
1557                        editor.set_render_diff_hunk_controls(
1558                            diff_hunk_controls(&thread, workspace.clone()),
1559                            cx,
1560                        );
1561                        editor.set_expand_all_diff_hunks(cx);
1562                        editor.register_addon(EditorAgentDiffAddon);
1563                    });
1564                } else {
1565                    unaffected.remove(weak_editor);
1566                }
1567
1568                if reviewing_state == EditorState::Reviewing
1569                    && previous_state != Some(reviewing_state)
1570                {
1571                    // Jump to first hunk when we enter review mode
1572                    editor.update(cx, |editor, cx| {
1573                        let snapshot = multibuffer.read(cx).snapshot(cx);
1574                        if let Some(first_hunk) = snapshot.diff_hunks().next() {
1575                            let first_hunk_start = first_hunk.multi_buffer_range().start;
1576
1577                            editor.change_selections(
1578                                SelectionEffects::scroll(Autoscroll::center()),
1579                                window,
1580                                cx,
1581                                |selections| {
1582                                    selections.select_ranges([first_hunk_start..first_hunk_start])
1583                                },
1584                            );
1585                        }
1586                    });
1587                }
1588            }
1589        }
1590
1591        // Remove editors from this workspace that are no longer under review
1592        for (editor, _) in unaffected {
1593            // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1594            // but that would add another lookup in `AgentDiff::editor_state`
1595            // which gets called much more frequently.
1596            let in_workspace = editor
1597                .read_with(cx, |editor, _cx| editor.workspace())
1598                .ok()
1599                .flatten()
1600                .is_some_and(|editor_workspace| {
1601                    editor_workspace.entity_id() == workspace.entity_id()
1602                });
1603
1604            if in_workspace {
1605                editor
1606                    .update(cx, |editor, cx| {
1607                        editor.end_temporary_diff_override(cx);
1608                        editor.unregister_addon::<EditorAgentDiffAddon>();
1609                    })
1610                    .ok();
1611                self.reviewing_editors.remove(&editor);
1612            }
1613        }
1614
1615        cx.notify();
1616    }
1617
1618    fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState {
1619        self.reviewing_editors
1620            .get(editor)
1621            .cloned()
1622            .unwrap_or(EditorState::Idle)
1623    }
1624
1625    fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1626        let Some(workspace) = editor.read(cx).workspace() else {
1627            return;
1628        };
1629
1630        let Some(WorkspaceThread { thread, .. }) =
1631            self.workspace_threads.get(&workspace.downgrade())
1632        else {
1633            return;
1634        };
1635
1636        let Some(thread) = thread.upgrade() else {
1637            return;
1638        };
1639
1640        AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1641    }
1642
1643    fn keep_all(
1644        editor: &Entity<Editor>,
1645        thread: &Entity<AcpThread>,
1646        _workspace: &WeakEntity<Workspace>,
1647        window: &mut Window,
1648        cx: &mut App,
1649    ) -> PostReviewState {
1650        editor.update(cx, |editor, cx| {
1651            let snapshot = editor.buffer().read(cx).snapshot(cx);
1652            keep_edits_in_ranges(
1653                editor,
1654                &snapshot,
1655                thread,
1656                vec![editor::Anchor::min()..editor::Anchor::max()],
1657                window,
1658                cx,
1659            );
1660        });
1661        PostReviewState::AllReviewed
1662    }
1663
1664    fn reject_all(
1665        editor: &Entity<Editor>,
1666        thread: &Entity<AcpThread>,
1667        workspace: &WeakEntity<Workspace>,
1668        window: &mut Window,
1669        cx: &mut App,
1670    ) -> PostReviewState {
1671        editor.update(cx, |editor, cx| {
1672            let snapshot = editor.buffer().read(cx).snapshot(cx);
1673            reject_edits_in_ranges(
1674                editor,
1675                &snapshot,
1676                thread,
1677                vec![editor::Anchor::min()..editor::Anchor::max()],
1678                workspace.clone(),
1679                window,
1680                cx,
1681            );
1682        });
1683        PostReviewState::AllReviewed
1684    }
1685
1686    fn keep(
1687        editor: &Entity<Editor>,
1688        thread: &Entity<AcpThread>,
1689        _workspace: &WeakEntity<Workspace>,
1690        window: &mut Window,
1691        cx: &mut App,
1692    ) -> PostReviewState {
1693        editor.update(cx, |editor, cx| {
1694            let snapshot = editor.buffer().read(cx).snapshot(cx);
1695            keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1696            Self::post_review_state(&snapshot)
1697        })
1698    }
1699
1700    fn reject(
1701        editor: &Entity<Editor>,
1702        thread: &Entity<AcpThread>,
1703        workspace: &WeakEntity<Workspace>,
1704        window: &mut Window,
1705        cx: &mut App,
1706    ) -> PostReviewState {
1707        editor.update(cx, |editor, cx| {
1708            let snapshot = editor.buffer().read(cx).snapshot(cx);
1709            reject_edits_in_selection(editor, &snapshot, thread, workspace.clone(), window, cx);
1710            Self::post_review_state(&snapshot)
1711        })
1712    }
1713
1714    fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1715        for (i, _) in snapshot.diff_hunks().enumerate() {
1716            if i > 0 {
1717                return PostReviewState::Pending;
1718            }
1719        }
1720        PostReviewState::AllReviewed
1721    }
1722
1723    fn review_in_active_editor(
1724        &mut self,
1725        workspace: &mut Workspace,
1726        review: impl Fn(
1727            &Entity<Editor>,
1728            &Entity<AcpThread>,
1729            &WeakEntity<Workspace>,
1730            &mut Window,
1731            &mut App,
1732        ) -> PostReviewState,
1733        window: &mut Window,
1734        cx: &mut Context<Self>,
1735    ) -> Option<Task<Result<()>>> {
1736        let active_item = workspace.active_item(cx)?;
1737        let editor = active_item.act_as::<Editor>(cx)?;
1738
1739        if !matches!(
1740            self.editor_state(&editor.downgrade()),
1741            EditorState::Reviewing
1742        ) {
1743            return None;
1744        }
1745
1746        let WorkspaceThread { thread, .. } =
1747            self.workspace_threads.get(&workspace.weak_handle())?;
1748
1749        let thread = thread.upgrade()?;
1750
1751        let review_result = review(&editor, &thread, &workspace.weak_handle(), window, cx);
1752
1753        if matches!(review_result, PostReviewState::AllReviewed)
1754            && let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton()
1755        {
1756            let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
1757
1758            let mut keys = changed_buffers.keys();
1759            keys.find(|k| *k == &curr_buffer);
1760            let next_project_path = keys
1761                .next()
1762                .filter(|k| *k != &curr_buffer)
1763                .and_then(|after| after.read(cx).project_path(cx));
1764
1765            if let Some(path) = next_project_path {
1766                let task = workspace.open_path(path, None, true, window, cx);
1767                let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1768                return Some(task);
1769            }
1770        }
1771
1772        Some(Task::ready(Ok(())))
1773    }
1774}
1775
1776enum PostReviewState {
1777    AllReviewed,
1778    Pending,
1779}
1780
1781pub struct EditorAgentDiffAddon;
1782
1783impl editor::Addon for EditorAgentDiffAddon {
1784    fn to_any(&self) -> &dyn std::any::Any {
1785        self
1786    }
1787
1788    fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1789        key_context.add("agent_diff");
1790        key_context.add("editor_agent_diff");
1791    }
1792}
1793
1794#[cfg(test)]
1795mod tests {
1796    use super::*;
1797    use crate::Keep;
1798    use acp_thread::AgentConnection as _;
1799    use agent_settings::AgentSettings;
1800    use editor::EditorSettings;
1801    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
1802    use project::{FakeFs, Project};
1803    use serde_json::json;
1804    use settings::SettingsStore;
1805    use std::{path::Path, rc::Rc};
1806    use util::path;
1807    use workspace::MultiWorkspace;
1808
1809    #[gpui::test]
1810    async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1811        cx.update(|cx| {
1812            let settings_store = SettingsStore::test(cx);
1813            cx.set_global(settings_store);
1814            prompt_store::init(cx);
1815            theme::init(theme::LoadThemes::JustBase, cx);
1816            language_model::init_settings(cx);
1817        });
1818
1819        let fs = FakeFs::new(cx.executor());
1820        fs.insert_tree(
1821            path!("/test"),
1822            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1823        )
1824        .await;
1825        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1826        let buffer_path = project
1827            .read_with(cx, |project, cx| {
1828                project.find_project_path("test/file1", cx)
1829            })
1830            .unwrap();
1831
1832        let connection = Rc::new(acp_thread::StubAgentConnection::new());
1833        let thread = cx
1834            .update(|cx| {
1835                connection
1836                    .clone()
1837                    .new_session(project.clone(), Path::new(path!("/test")), cx)
1838            })
1839            .await
1840            .unwrap();
1841
1842        let action_log = cx.read(|cx| thread.read(cx).action_log().clone());
1843
1844        let (multi_workspace, cx) =
1845            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1846        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1847        let agent_diff = cx.new_window_entity(|window, cx| {
1848            AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1849        });
1850        let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1851
1852        let buffer = project
1853            .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1854            .await
1855            .unwrap();
1856        cx.update(|_, cx| {
1857            action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
1858            buffer.update(cx, |buffer, cx| {
1859                buffer
1860                    .edit(
1861                        [
1862                            (Point::new(1, 1)..Point::new(1, 2), "E"),
1863                            (Point::new(3, 2)..Point::new(3, 3), "L"),
1864                            (Point::new(5, 0)..Point::new(5, 1), "P"),
1865                            (Point::new(7, 1)..Point::new(7, 2), "W"),
1866                        ],
1867                        None,
1868                        cx,
1869                    )
1870                    .unwrap()
1871            });
1872            action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1873        });
1874        cx.run_until_parked();
1875
1876        // When opening the assistant diff, the cursor is positioned on the first hunk.
1877        assert_eq!(
1878            editor.read_with(cx, |editor, cx| editor.text(cx)),
1879            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1880        );
1881        assert_eq!(
1882            editor
1883                .update(cx, |editor, cx| editor
1884                    .selections
1885                    .newest::<Point>(&editor.display_snapshot(cx)))
1886                .range(),
1887            Point::new(1, 0)..Point::new(1, 0)
1888        );
1889
1890        // After keeping a hunk, the cursor should be positioned on the second hunk.
1891        agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1892        cx.run_until_parked();
1893        assert_eq!(
1894            editor.read_with(cx, |editor, cx| editor.text(cx)),
1895            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1896        );
1897        assert_eq!(
1898            editor
1899                .update(cx, |editor, cx| editor
1900                    .selections
1901                    .newest::<Point>(&editor.display_snapshot(cx)))
1902                .range(),
1903            Point::new(3, 0)..Point::new(3, 0)
1904        );
1905
1906        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1907        editor.update_in(cx, |editor, window, cx| {
1908            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1909                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1910            });
1911        });
1912        agent_diff.update_in(cx, |diff, window, cx| {
1913            diff.reject(&crate::Reject, window, cx)
1914        });
1915        cx.run_until_parked();
1916        assert_eq!(
1917            editor.read_with(cx, |editor, cx| editor.text(cx)),
1918            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1919        );
1920        assert_eq!(
1921            editor
1922                .update(cx, |editor, cx| editor
1923                    .selections
1924                    .newest::<Point>(&editor.display_snapshot(cx)))
1925                .range(),
1926            Point::new(3, 0)..Point::new(3, 0)
1927        );
1928
1929        // Keeping a range that doesn't intersect the current selection doesn't move it.
1930        agent_diff.update_in(cx, |_diff, window, cx| {
1931            let position = editor
1932                .read(cx)
1933                .buffer()
1934                .read(cx)
1935                .read(cx)
1936                .anchor_before(Point::new(7, 0));
1937            editor.update(cx, |editor, cx| {
1938                let snapshot = editor.buffer().read(cx).snapshot(cx);
1939                keep_edits_in_ranges(
1940                    editor,
1941                    &snapshot,
1942                    &thread,
1943                    vec![position..position],
1944                    window,
1945                    cx,
1946                )
1947            });
1948        });
1949        cx.run_until_parked();
1950        assert_eq!(
1951            editor.read_with(cx, |editor, cx| editor.text(cx)),
1952            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1953        );
1954        assert_eq!(
1955            editor
1956                .update(cx, |editor, cx| editor
1957                    .selections
1958                    .newest::<Point>(&editor.display_snapshot(cx)))
1959                .range(),
1960            Point::new(3, 0)..Point::new(3, 0)
1961        );
1962    }
1963
1964    #[gpui::test]
1965    async fn test_single_file_review_diff(cx: &mut TestAppContext) {
1966        cx.update(|cx| {
1967            let settings_store = SettingsStore::test(cx);
1968            cx.set_global(settings_store);
1969            prompt_store::init(cx);
1970            theme::init(theme::LoadThemes::JustBase, cx);
1971            language_model::init_settings(cx);
1972            workspace::register_project_item::<Editor>(cx);
1973        });
1974
1975        cx.update(|cx| {
1976            SettingsStore::update_global(cx, |store, _cx| {
1977                let mut agent_settings = store.get::<AgentSettings>(None).clone();
1978                agent_settings.single_file_review = true;
1979                store.override_global(agent_settings);
1980            });
1981        });
1982
1983        let fs = FakeFs::new(cx.executor());
1984        fs.insert_tree(
1985            path!("/test"),
1986            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1987        )
1988        .await;
1989        fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1990            .await;
1991
1992        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1993        let buffer_path1 = project
1994            .read_with(cx, |project, cx| {
1995                project.find_project_path("test/file1", cx)
1996            })
1997            .unwrap();
1998        let buffer_path2 = project
1999            .read_with(cx, |project, cx| {
2000                project.find_project_path("test/file2", cx)
2001            })
2002            .unwrap();
2003
2004        let (multi_workspace, cx) =
2005            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2006        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2007
2008        // Add the diff toolbar to the active pane
2009        let diff_toolbar = cx.new_window_entity(|_, cx| AgentDiffToolbar::new(cx));
2010
2011        workspace.update_in(cx, {
2012            let diff_toolbar = diff_toolbar.clone();
2013
2014            move |workspace, window, cx| {
2015                workspace.active_pane().update(cx, |pane, cx| {
2016                    pane.toolbar().update(cx, |toolbar, cx| {
2017                        toolbar.add_item(diff_toolbar, window, cx);
2018                    });
2019                })
2020            }
2021        });
2022
2023        let connection = Rc::new(acp_thread::StubAgentConnection::new());
2024        let thread = cx
2025            .update(|_, cx| {
2026                connection
2027                    .clone()
2028                    .new_session(project.clone(), Path::new(path!("/test")), cx)
2029            })
2030            .await
2031            .unwrap();
2032        let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
2033
2034        // Set the active thread
2035        cx.update(|window, cx| {
2036            AgentDiff::set_active_thread(&workspace.downgrade(), thread.clone(), window, cx)
2037        });
2038
2039        let buffer1 = project
2040            .update(cx, |project, cx| {
2041                project.open_buffer(buffer_path1.clone(), cx)
2042            })
2043            .await
2044            .unwrap();
2045        let buffer2 = project
2046            .update(cx, |project, cx| {
2047                project.open_buffer(buffer_path2.clone(), cx)
2048            })
2049            .await
2050            .unwrap();
2051
2052        // Open an editor for buffer1
2053        let editor1 = cx.new_window_entity(|window, cx| {
2054            Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
2055        });
2056
2057        workspace.update_in(cx, |workspace, window, cx| {
2058            workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
2059        });
2060        cx.run_until_parked();
2061
2062        // Toolbar knows about the current editor, but it's hidden since there are no changes yet
2063        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2064            toolbar.active_item,
2065            Some(AgentDiffToolbarItem::Editor {
2066                state: EditorState::Idle,
2067                ..
2068            })
2069        )));
2070        assert_eq!(
2071            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2072            ToolbarItemLocation::Hidden
2073        );
2074
2075        // Make changes
2076        cx.update(|_, cx| {
2077            action_log.update(cx, |log, cx| log.buffer_read(buffer1.clone(), cx));
2078            buffer1.update(cx, |buffer, cx| {
2079                buffer
2080                    .edit(
2081                        [
2082                            (Point::new(1, 1)..Point::new(1, 2), "E"),
2083                            (Point::new(3, 2)..Point::new(3, 3), "L"),
2084                            (Point::new(5, 0)..Point::new(5, 1), "P"),
2085                            (Point::new(7, 1)..Point::new(7, 2), "W"),
2086                        ],
2087                        None,
2088                        cx,
2089                    )
2090                    .unwrap()
2091            });
2092            action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
2093
2094            action_log.update(cx, |log, cx| log.buffer_read(buffer2.clone(), cx));
2095            buffer2.update(cx, |buffer, cx| {
2096                buffer
2097                    .edit(
2098                        [
2099                            (Point::new(0, 0)..Point::new(0, 1), "A"),
2100                            (Point::new(2, 1)..Point::new(2, 2), "H"),
2101                        ],
2102                        None,
2103                        cx,
2104                    )
2105                    .unwrap();
2106            });
2107            action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
2108        });
2109        cx.run_until_parked();
2110
2111        // The already opened editor displays the diff and the cursor is at the first hunk
2112        assert_eq!(
2113            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2114            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2115        );
2116        assert_eq!(
2117            editor1
2118                .update(cx, |editor, cx| editor
2119                    .selections
2120                    .newest::<Point>(&editor.display_snapshot(cx)))
2121                .range(),
2122            Point::new(1, 0)..Point::new(1, 0)
2123        );
2124
2125        // The toolbar is displayed in the right state
2126        assert_eq!(
2127            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2128            ToolbarItemLocation::PrimaryRight
2129        );
2130        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2131            toolbar.active_item,
2132            Some(AgentDiffToolbarItem::Editor {
2133                state: EditorState::Reviewing,
2134                ..
2135            })
2136        )));
2137
2138        // The toolbar respects its setting
2139        override_toolbar_agent_review_setting(false, cx);
2140        assert_eq!(
2141            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2142            ToolbarItemLocation::Hidden
2143        );
2144        override_toolbar_agent_review_setting(true, cx);
2145        assert_eq!(
2146            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2147            ToolbarItemLocation::PrimaryRight
2148        );
2149
2150        // After keeping a hunk, the cursor should be positioned on the second hunk.
2151        workspace.update(cx, |_, cx| {
2152            cx.dispatch_action(&Keep);
2153        });
2154        cx.run_until_parked();
2155        assert_eq!(
2156            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2157            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2158        );
2159        assert_eq!(
2160            editor1
2161                .update(cx, |editor, cx| editor
2162                    .selections
2163                    .newest::<Point>(&editor.display_snapshot(cx)))
2164                .range(),
2165            Point::new(3, 0)..Point::new(3, 0)
2166        );
2167
2168        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
2169        editor1.update_in(cx, |editor, window, cx| {
2170            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
2171                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
2172            });
2173        });
2174        workspace.update(cx, |_, cx| {
2175            cx.dispatch_action(&Reject);
2176        });
2177        cx.run_until_parked();
2178        assert_eq!(
2179            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2180            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
2181        );
2182        assert_eq!(
2183            editor1
2184                .update(cx, |editor, cx| editor
2185                    .selections
2186                    .newest::<Point>(&editor.display_snapshot(cx)))
2187                .range(),
2188            Point::new(3, 0)..Point::new(3, 0)
2189        );
2190
2191        // Keeping a range that doesn't intersect the current selection doesn't move it.
2192        editor1.update_in(cx, |editor, window, cx| {
2193            let buffer = editor.buffer().read(cx);
2194            let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2195            let snapshot = buffer.snapshot(cx);
2196            keep_edits_in_ranges(
2197                editor,
2198                &snapshot,
2199                &thread,
2200                vec![position..position],
2201                window,
2202                cx,
2203            )
2204        });
2205        cx.run_until_parked();
2206        assert_eq!(
2207            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2208            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2209        );
2210        assert_eq!(
2211            editor1
2212                .update(cx, |editor, cx| editor
2213                    .selections
2214                    .newest::<Point>(&editor.display_snapshot(cx)))
2215                .range(),
2216            Point::new(3, 0)..Point::new(3, 0)
2217        );
2218
2219        // Reviewing the last change opens the next changed buffer
2220        workspace
2221            .update_in(cx, |workspace, window, cx| {
2222                AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2223                    agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2224                })
2225            })
2226            .unwrap()
2227            .await
2228            .unwrap();
2229
2230        cx.run_until_parked();
2231
2232        let editor2 = workspace.update(cx, |workspace, cx| {
2233            workspace.active_item_as::<Editor>(cx).unwrap()
2234        });
2235
2236        let editor2_path = editor2
2237            .read_with(cx, |editor, cx| editor.project_path(cx))
2238            .unwrap();
2239        assert_eq!(editor2_path, buffer_path2);
2240
2241        assert_eq!(
2242            editor2.read_with(cx, |editor, cx| editor.text(cx)),
2243            "abc\nAbc\ndef\nghi\ngHi"
2244        );
2245        assert_eq!(
2246            editor2
2247                .update(cx, |editor, cx| editor
2248                    .selections
2249                    .newest::<Point>(&editor.display_snapshot(cx)))
2250                .range(),
2251            Point::new(0, 0)..Point::new(0, 0)
2252        );
2253
2254        // Editor 1 toolbar is hidden since all changes have been reviewed
2255        workspace.update_in(cx, |workspace, window, cx| {
2256            workspace.activate_item(&editor1, true, true, window, cx)
2257        });
2258
2259        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2260            toolbar.active_item,
2261            Some(AgentDiffToolbarItem::Editor {
2262                state: EditorState::Idle,
2263                ..
2264            })
2265        )));
2266        assert_eq!(
2267            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2268            ToolbarItemLocation::Hidden
2269        );
2270    }
2271
2272    fn override_toolbar_agent_review_setting(active: bool, cx: &mut VisualTestContext) {
2273        cx.update(|_window, cx| {
2274            SettingsStore::update_global(cx, |store, _cx| {
2275                let mut editor_settings = store.get::<EditorSettings>(None).clone();
2276                editor_settings.toolbar.agent_review = active;
2277                store.override_global(editor_settings);
2278            })
2279        });
2280        cx.run_until_parked();
2281    }
2282}