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