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