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