agent_diff.rs

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