inline_assistant.rs

   1use language_model::AnthropicEventData;
   2use language_model::report_anthropic_event;
   3use std::cmp;
   4use std::mem;
   5use std::ops::Range;
   6use std::rc::Rc;
   7use std::sync::Arc;
   8use uuid::Uuid;
   9
  10use crate::acp::AcpThreadHistory;
  11use crate::context::load_context;
  12use crate::mention_set::MentionSet;
  13use crate::{
  14    AgentPanel,
  15    buffer_codegen::{BufferCodegen, CodegenAlternative, CodegenEvent},
  16    inline_prompt_editor::{CodegenStatus, InlineAssistId, PromptEditor, PromptEditorEvent},
  17    terminal_inline_assistant::TerminalInlineAssistant,
  18};
  19use agent::ThreadStore;
  20use agent_settings::AgentSettings;
  21use anyhow::{Context as _, Result};
  22use collections::{HashMap, HashSet, VecDeque, hash_map};
  23use editor::EditorSnapshot;
  24use editor::MultiBufferOffset;
  25use editor::RowExt;
  26use editor::SelectionEffects;
  27use editor::scroll::ScrollOffset;
  28use editor::{
  29    Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorEvent, ExcerptId, ExcerptRange,
  30    HighlightKey, MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint,
  31    actions::SelectAll,
  32    display_map::{
  33        BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, EditorMargins,
  34        RenderBlock, ToDisplayPoint,
  35    },
  36};
  37use fs::Fs;
  38use futures::{FutureExt, channel::mpsc};
  39use gpui::{
  40    App, Context, Entity, Focusable, Global, HighlightStyle, Subscription, Task, UpdateGlobal,
  41    WeakEntity, Window, point,
  42};
  43use language::{Buffer, Point, Selection, TransactionId};
  44use language_model::{ConfigurationError, ConfiguredModel, LanguageModelRegistry};
  45use multi_buffer::MultiBufferRow;
  46use parking_lot::Mutex;
  47use project::{CodeAction, DisableAiSettings, LspAction, Project, ProjectTransaction};
  48use prompt_store::{PromptBuilder, PromptStore};
  49use settings::{Settings, SettingsStore};
  50
  51use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
  52use text::{OffsetRangeExt, ToPoint as _};
  53use ui::prelude::*;
  54use util::{RangeExt, ResultExt, maybe};
  55use workspace::{
  56    ItemHandle, NotificationSource, Toast, Workspace, dock::Panel, notifications::NotificationId,
  57};
  58use zed_actions::agent::OpenSettings;
  59
  60pub fn init(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>, cx: &mut App) {
  61    cx.set_global(InlineAssistant::new(fs, prompt_builder));
  62
  63    cx.observe_global::<SettingsStore>(|cx| {
  64        if DisableAiSettings::get_global(cx).disable_ai {
  65            // Hide any active inline assist UI when AI is disabled
  66            InlineAssistant::update_global(cx, |assistant, cx| {
  67                assistant.cancel_all_active_completions(cx);
  68            });
  69        }
  70    })
  71    .detach();
  72
  73    cx.observe_new(|_workspace: &mut Workspace, window, cx| {
  74        let Some(window) = window else {
  75            return;
  76        };
  77        let workspace = cx.entity();
  78        InlineAssistant::update_global(cx, |inline_assistant, cx| {
  79            inline_assistant.register_workspace(&workspace, window, cx)
  80        });
  81    })
  82    .detach();
  83}
  84
  85const PROMPT_HISTORY_MAX_LEN: usize = 20;
  86
  87enum InlineAssistTarget {
  88    Editor(Entity<Editor>),
  89    Terminal(Entity<TerminalView>),
  90}
  91
  92pub struct InlineAssistant {
  93    next_assist_id: InlineAssistId,
  94    next_assist_group_id: InlineAssistGroupId,
  95    assists: HashMap<InlineAssistId, InlineAssist>,
  96    assists_by_editor: HashMap<WeakEntity<Editor>, EditorInlineAssists>,
  97    assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,
  98    confirmed_assists: HashMap<InlineAssistId, Entity<CodegenAlternative>>,
  99    prompt_history: VecDeque<String>,
 100    prompt_builder: Arc<PromptBuilder>,
 101    fs: Arc<dyn Fs>,
 102    _inline_assistant_completions: Option<mpsc::UnboundedSender<anyhow::Result<InlineAssistId>>>,
 103}
 104
 105impl Global for InlineAssistant {}
 106
 107impl InlineAssistant {
 108    pub fn new(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>) -> Self {
 109        Self {
 110            next_assist_id: InlineAssistId::default(),
 111            next_assist_group_id: InlineAssistGroupId::default(),
 112            assists: HashMap::default(),
 113            assists_by_editor: HashMap::default(),
 114            assist_groups: HashMap::default(),
 115            confirmed_assists: HashMap::default(),
 116            prompt_history: VecDeque::default(),
 117            prompt_builder,
 118            fs,
 119            _inline_assistant_completions: None,
 120        }
 121    }
 122
 123    pub fn register_workspace(
 124        &mut self,
 125        workspace: &Entity<Workspace>,
 126        window: &mut Window,
 127        cx: &mut App,
 128    ) {
 129        window
 130            .subscribe(workspace, cx, |workspace, event, window, cx| {
 131                Self::update_global(cx, |this, cx| {
 132                    this.handle_workspace_event(workspace, event, window, cx)
 133                });
 134            })
 135            .detach();
 136
 137        let workspace = workspace.downgrade();
 138        cx.observe_global::<SettingsStore>(move |cx| {
 139            let Some(workspace) = workspace.upgrade() else {
 140                return;
 141            };
 142            let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
 143                return;
 144            };
 145            let enabled = AgentSettings::get_global(cx).enabled(cx);
 146            terminal_panel.update(cx, |terminal_panel, cx| {
 147                terminal_panel.set_assistant_enabled(enabled, cx)
 148            });
 149        })
 150        .detach();
 151    }
 152
 153    /// Hides all active inline assists when AI is disabled
 154    pub fn cancel_all_active_completions(&mut self, cx: &mut App) {
 155        // Cancel all active completions in editors
 156        for (editor_handle, _) in self.assists_by_editor.iter() {
 157            if let Some(editor) = editor_handle.upgrade() {
 158                let windows = cx.windows();
 159                if !windows.is_empty() {
 160                    let window = windows[0];
 161                    let _ = window.update(cx, |_, window, cx| {
 162                        editor.update(cx, |editor, cx| {
 163                            if editor.has_active_edit_prediction() {
 164                                editor.cancel(&Default::default(), window, cx);
 165                            }
 166                        });
 167                    });
 168                }
 169            }
 170        }
 171    }
 172
 173    fn handle_workspace_event(
 174        &mut self,
 175        workspace: Entity<Workspace>,
 176        event: &workspace::Event,
 177        window: &mut Window,
 178        cx: &mut App,
 179    ) {
 180        match event {
 181            workspace::Event::UserSavedItem { item, .. } => {
 182                // When the user manually saves an editor, automatically accepts all finished transformations.
 183                if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx))
 184                    && let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade())
 185                {
 186                    for assist_id in editor_assists.assist_ids.clone() {
 187                        let assist = &self.assists[&assist_id];
 188                        if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
 189                            self.finish_assist(assist_id, false, window, cx)
 190                        }
 191                    }
 192                }
 193            }
 194            workspace::Event::ItemAdded { item } => {
 195                self.register_workspace_item(&workspace, item.as_ref(), window, cx);
 196            }
 197            _ => (),
 198        }
 199    }
 200
 201    fn register_workspace_item(
 202        &mut self,
 203        workspace: &Entity<Workspace>,
 204        item: &dyn ItemHandle,
 205        window: &mut Window,
 206        cx: &mut App,
 207    ) {
 208        let is_ai_enabled = !DisableAiSettings::get_global(cx).disable_ai;
 209
 210        if let Some(editor) = item.act_as::<Editor>(cx) {
 211            editor.update(cx, |editor, cx| {
 212                if is_ai_enabled {
 213                    editor.add_code_action_provider(
 214                        Rc::new(AssistantCodeActionProvider {
 215                            editor: cx.entity().downgrade(),
 216                            workspace: workspace.downgrade(),
 217                        }),
 218                        window,
 219                        cx,
 220                    );
 221
 222                    if DisableAiSettings::get_global(cx).disable_ai {
 223                        // Cancel any active edit predictions
 224                        if editor.has_active_edit_prediction() {
 225                            editor.cancel(&Default::default(), window, cx);
 226                        }
 227                    }
 228                } else {
 229                    editor.remove_code_action_provider(
 230                        ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
 231                        window,
 232                        cx,
 233                    );
 234                }
 235            });
 236        }
 237    }
 238
 239    pub fn inline_assist(
 240        workspace: &mut Workspace,
 241        action: &zed_actions::assistant::InlineAssist,
 242        window: &mut Window,
 243        cx: &mut Context<Workspace>,
 244    ) {
 245        if !AgentSettings::get_global(cx).enabled(cx) {
 246            return;
 247        }
 248
 249        let Some(inline_assist_target) = Self::resolve_inline_assist_target(
 250            workspace,
 251            workspace.panel::<AgentPanel>(cx),
 252            window,
 253            cx,
 254        ) else {
 255            return;
 256        };
 257
 258        let configuration_error = || {
 259            let model_registry = LanguageModelRegistry::read_global(cx);
 260            model_registry.configuration_error(model_registry.inline_assistant_model(), cx)
 261        };
 262
 263        let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) else {
 264            return;
 265        };
 266        let agent_panel = agent_panel.read(cx);
 267
 268        let prompt_store = agent_panel.prompt_store().as_ref().cloned();
 269        let thread_store = agent_panel.thread_store().clone();
 270        let history = agent_panel.history().downgrade();
 271
 272        let handle_assist =
 273            |window: &mut Window, cx: &mut Context<Workspace>| match inline_assist_target {
 274                InlineAssistTarget::Editor(active_editor) => {
 275                    InlineAssistant::update_global(cx, |assistant, cx| {
 276                        assistant.assist(
 277                            &active_editor,
 278                            cx.entity().downgrade(),
 279                            workspace.project().downgrade(),
 280                            thread_store,
 281                            prompt_store,
 282                            history,
 283                            action.prompt.clone(),
 284                            window,
 285                            cx,
 286                        );
 287                    })
 288                }
 289                InlineAssistTarget::Terminal(active_terminal) => {
 290                    TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 291                        assistant.assist(
 292                            &active_terminal,
 293                            cx.entity().downgrade(),
 294                            workspace.project().downgrade(),
 295                            thread_store,
 296                            prompt_store,
 297                            history,
 298                            action.prompt.clone(),
 299                            window,
 300                            cx,
 301                        );
 302                    });
 303                }
 304            };
 305
 306        if let Some(error) = configuration_error() {
 307            if let ConfigurationError::ProviderNotAuthenticated(provider) = error {
 308                cx.spawn(async move |_, cx| {
 309                    cx.update(|cx| provider.authenticate(cx)).await?;
 310                    anyhow::Ok(())
 311                })
 312                .detach_and_log_err(cx);
 313
 314                if configuration_error().is_none() {
 315                    handle_assist(window, cx);
 316                }
 317            } else {
 318                cx.spawn_in(window, async move |_, cx| {
 319                    let answer = cx
 320                        .prompt(
 321                            gpui::PromptLevel::Warning,
 322                            &error.to_string(),
 323                            None,
 324                            &["Configure", "Cancel"],
 325                        )
 326                        .await
 327                        .ok();
 328                    if let Some(answer) = answer
 329                        && answer == 0
 330                    {
 331                        cx.update(|window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
 332                            .ok();
 333                    }
 334                    anyhow::Ok(())
 335                })
 336                .detach_and_log_err(cx);
 337            }
 338        } else {
 339            handle_assist(window, cx);
 340        }
 341    }
 342
 343    fn codegen_ranges(
 344        &mut self,
 345        editor: &Entity<Editor>,
 346        snapshot: &EditorSnapshot,
 347        window: &mut Window,
 348        cx: &mut App,
 349    ) -> Option<(Vec<Range<Anchor>>, Selection<Point>)> {
 350        let (initial_selections, newest_selection) = editor.update(cx, |editor, _| {
 351            (
 352                editor.selections.all::<Point>(&snapshot.display_snapshot),
 353                editor
 354                    .selections
 355                    .newest::<Point>(&snapshot.display_snapshot),
 356            )
 357        });
 358
 359        // Check if there is already an inline assistant that contains the
 360        // newest selection, if there is, focus it
 361        if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 362            for assist_id in &editor_assists.assist_ids {
 363                let assist = &self.assists[assist_id];
 364                let range = assist.range.to_point(&snapshot.buffer_snapshot());
 365                if range.start.row <= newest_selection.start.row
 366                    && newest_selection.end.row <= range.end.row
 367                {
 368                    self.focus_assist(*assist_id, window, cx);
 369                    return None;
 370                }
 371            }
 372        }
 373
 374        let mut selections = Vec::<Selection<Point>>::new();
 375        let mut newest_selection = None;
 376        for mut selection in initial_selections {
 377            if selection.end == selection.start
 378                && let Some(fold) =
 379                    snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
 380            {
 381                selection.start = fold.range().start;
 382                selection.end = fold.range().end;
 383                if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot().max_row() {
 384                    let chars = snapshot
 385                        .buffer_snapshot()
 386                        .chars_at(Point::new(selection.end.row + 1, 0));
 387
 388                    for c in chars {
 389                        if c == '\n' {
 390                            break;
 391                        }
 392                        if c.is_whitespace() {
 393                            continue;
 394                        }
 395                        if snapshot
 396                            .language_at(selection.end)
 397                            .is_some_and(|language| language.config().brackets.is_closing_brace(c))
 398                        {
 399                            selection.end.row += 1;
 400                            selection.end.column = snapshot
 401                                .buffer_snapshot()
 402                                .line_len(MultiBufferRow(selection.end.row));
 403                        }
 404                    }
 405                }
 406            } else {
 407                selection.start.column = 0;
 408                // If the selection ends at the start of the line, we don't want to include it.
 409                if selection.end.column == 0 && selection.start.row != selection.end.row {
 410                    selection.end.row -= 1;
 411                }
 412                selection.end.column = snapshot
 413                    .buffer_snapshot()
 414                    .line_len(MultiBufferRow(selection.end.row));
 415            }
 416
 417            if let Some(prev_selection) = selections.last_mut()
 418                && selection.start <= prev_selection.end
 419            {
 420                prev_selection.end = selection.end;
 421                continue;
 422            }
 423
 424            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 425            if selection.id > latest_selection.id {
 426                *latest_selection = selection.clone();
 427            }
 428            selections.push(selection);
 429        }
 430        let snapshot = &snapshot.buffer_snapshot();
 431        let newest_selection = newest_selection.unwrap();
 432
 433        let mut codegen_ranges = Vec::new();
 434        for (buffer, buffer_range, excerpt_id) in
 435            snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
 436                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 437            }))
 438        {
 439            let anchor_range = Anchor::range_in_buffer(
 440                excerpt_id,
 441                buffer.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
 442            );
 443
 444            codegen_ranges.push(anchor_range);
 445
 446            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
 447                telemetry::event!(
 448                    "Assistant Invoked",
 449                    kind = "inline",
 450                    phase = "invoked",
 451                    model = model.model.telemetry_id(),
 452                    model_provider = model.provider.id().to_string(),
 453                    language_name = buffer.language().map(|language| language.name().to_proto())
 454                );
 455
 456                report_anthropic_event(
 457                    &model.model,
 458                    AnthropicEventData {
 459                        completion_type: language_model::AnthropicCompletionType::Editor,
 460                        event: language_model::AnthropicEventType::Invoked,
 461                        language_name: buffer.language().map(|language| language.name().to_proto()),
 462                        message_id: None,
 463                    },
 464                    cx,
 465                );
 466            }
 467        }
 468
 469        Some((codegen_ranges, newest_selection))
 470    }
 471
 472    fn batch_assist(
 473        &mut self,
 474        editor: &Entity<Editor>,
 475        workspace: WeakEntity<Workspace>,
 476        project: WeakEntity<Project>,
 477        thread_store: Entity<ThreadStore>,
 478        prompt_store: Option<Entity<PromptStore>>,
 479        history: WeakEntity<AcpThreadHistory>,
 480        initial_prompt: Option<String>,
 481        window: &mut Window,
 482        codegen_ranges: &[Range<Anchor>],
 483        newest_selection: Option<Selection<Point>>,
 484        initial_transaction_id: Option<TransactionId>,
 485        cx: &mut App,
 486    ) -> Option<InlineAssistId> {
 487        let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 488
 489        let assist_group_id = self.next_assist_group_id.post_inc();
 490        let session_id = Uuid::new_v4();
 491        let prompt_buffer = cx.new(|cx| {
 492            MultiBuffer::singleton(
 493                cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
 494                cx,
 495            )
 496        });
 497
 498        let mut assists = Vec::new();
 499        let mut assist_to_focus = None;
 500
 501        for range in codegen_ranges {
 502            let assist_id = self.next_assist_id.post_inc();
 503            let codegen = cx.new(|cx| {
 504                BufferCodegen::new(
 505                    editor.read(cx).buffer().clone(),
 506                    range.clone(),
 507                    initial_transaction_id,
 508                    session_id,
 509                    self.prompt_builder.clone(),
 510                    cx,
 511                )
 512            });
 513
 514            let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 515            let prompt_editor = cx.new(|cx| {
 516                PromptEditor::new_buffer(
 517                    assist_id,
 518                    editor_margins,
 519                    self.prompt_history.clone(),
 520                    prompt_buffer.clone(),
 521                    codegen.clone(),
 522                    session_id,
 523                    self.fs.clone(),
 524                    thread_store.clone(),
 525                    prompt_store.clone(),
 526                    history.clone(),
 527                    project.clone(),
 528                    workspace.clone(),
 529                    window,
 530                    cx,
 531                )
 532            });
 533
 534            if let Some(newest_selection) = newest_selection.as_ref()
 535                && assist_to_focus.is_none()
 536            {
 537                let focus_assist = if newest_selection.reversed {
 538                    range.start.to_point(&snapshot) == newest_selection.start
 539                } else {
 540                    range.end.to_point(&snapshot) == newest_selection.end
 541                };
 542                if focus_assist {
 543                    assist_to_focus = Some(assist_id);
 544                }
 545            }
 546
 547            let [prompt_block_id, tool_description_block_id, end_block_id] =
 548                self.insert_assist_blocks(&editor, &range, &prompt_editor, cx);
 549
 550            assists.push((
 551                assist_id,
 552                range.clone(),
 553                prompt_editor,
 554                prompt_block_id,
 555                tool_description_block_id,
 556                end_block_id,
 557            ));
 558        }
 559
 560        let editor_assists = self
 561            .assists_by_editor
 562            .entry(editor.downgrade())
 563            .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
 564
 565        let assist_to_focus = if let Some(focus_id) = assist_to_focus {
 566            Some(focus_id)
 567        } else if assists.len() >= 1 {
 568            Some(assists[0].0)
 569        } else {
 570            None
 571        };
 572
 573        let mut assist_group = InlineAssistGroup::new();
 574        for (
 575            assist_id,
 576            range,
 577            prompt_editor,
 578            prompt_block_id,
 579            tool_description_block_id,
 580            end_block_id,
 581        ) in assists
 582        {
 583            let codegen = prompt_editor.read(cx).codegen().clone();
 584
 585            self.assists.insert(
 586                assist_id,
 587                InlineAssist::new(
 588                    assist_id,
 589                    assist_group_id,
 590                    editor,
 591                    &prompt_editor,
 592                    prompt_block_id,
 593                    tool_description_block_id,
 594                    end_block_id,
 595                    range,
 596                    codegen,
 597                    workspace.clone(),
 598                    window,
 599                    cx,
 600                ),
 601            );
 602            assist_group.assist_ids.push(assist_id);
 603            editor_assists.assist_ids.push(assist_id);
 604        }
 605
 606        self.assist_groups.insert(assist_group_id, assist_group);
 607
 608        assist_to_focus
 609    }
 610
 611    pub fn assist(
 612        &mut self,
 613        editor: &Entity<Editor>,
 614        workspace: WeakEntity<Workspace>,
 615        project: WeakEntity<Project>,
 616        thread_store: Entity<ThreadStore>,
 617        prompt_store: Option<Entity<PromptStore>>,
 618        history: WeakEntity<AcpThreadHistory>,
 619        initial_prompt: Option<String>,
 620        window: &mut Window,
 621        cx: &mut App,
 622    ) -> Option<InlineAssistId> {
 623        let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 624
 625        let Some((codegen_ranges, newest_selection)) =
 626            self.codegen_ranges(editor, &snapshot, window, cx)
 627        else {
 628            return None;
 629        };
 630
 631        let assist_to_focus = self.batch_assist(
 632            editor,
 633            workspace,
 634            project,
 635            thread_store,
 636            prompt_store,
 637            history,
 638            initial_prompt,
 639            window,
 640            &codegen_ranges,
 641            Some(newest_selection),
 642            None,
 643            cx,
 644        );
 645
 646        if let Some(assist_id) = assist_to_focus {
 647            self.focus_assist(assist_id, window, cx);
 648        }
 649
 650        assist_to_focus
 651    }
 652
 653    pub fn suggest_assist(
 654        &mut self,
 655        editor: &Entity<Editor>,
 656        mut range: Range<Anchor>,
 657        initial_prompt: String,
 658        initial_transaction_id: Option<TransactionId>,
 659        focus: bool,
 660        workspace: Entity<Workspace>,
 661        thread_store: Entity<ThreadStore>,
 662        prompt_store: Option<Entity<PromptStore>>,
 663        history: WeakEntity<AcpThreadHistory>,
 664        window: &mut Window,
 665        cx: &mut App,
 666    ) -> InlineAssistId {
 667        let buffer = editor.read(cx).buffer().clone();
 668        {
 669            let snapshot = buffer.read(cx).read(cx);
 670            range.start = range.start.bias_left(&snapshot);
 671            range.end = range.end.bias_right(&snapshot);
 672        }
 673
 674        let project = workspace.read(cx).project().downgrade();
 675
 676        let assist_id = self
 677            .batch_assist(
 678                editor,
 679                workspace.downgrade(),
 680                project,
 681                thread_store,
 682                prompt_store,
 683                history,
 684                Some(initial_prompt),
 685                window,
 686                &[range],
 687                None,
 688                initial_transaction_id,
 689                cx,
 690            )
 691            .expect("batch_assist returns an id if there's only one range");
 692
 693        if focus {
 694            self.focus_assist(assist_id, window, cx);
 695        }
 696
 697        assist_id
 698    }
 699
 700    fn insert_assist_blocks(
 701        &self,
 702        editor: &Entity<Editor>,
 703        range: &Range<Anchor>,
 704        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
 705        cx: &mut App,
 706    ) -> [CustomBlockId; 3] {
 707        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 708            prompt_editor
 709                .editor
 710                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 711        });
 712        let assist_blocks = vec![
 713            BlockProperties {
 714                style: BlockStyle::Sticky,
 715                placement: BlockPlacement::Above(range.start),
 716                height: Some(prompt_editor_height),
 717                render: build_assist_editor_renderer(prompt_editor),
 718                priority: 0,
 719            },
 720            // Placeholder for tool description - will be updated dynamically
 721            BlockProperties {
 722                style: BlockStyle::Flex,
 723                placement: BlockPlacement::Below(range.end),
 724                height: Some(0),
 725                render: Arc::new(|_cx| div().into_any_element()),
 726                priority: 0,
 727            },
 728            BlockProperties {
 729                style: BlockStyle::Sticky,
 730                placement: BlockPlacement::Below(range.end),
 731                height: None,
 732                render: Arc::new(|cx| {
 733                    v_flex()
 734                        .h_full()
 735                        .w_full()
 736                        .border_t_1()
 737                        .border_color(cx.theme().status().info_border)
 738                        .into_any_element()
 739                }),
 740                priority: 0,
 741            },
 742        ];
 743
 744        editor.update(cx, |editor, cx| {
 745            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 746            [block_ids[0], block_ids[1], block_ids[2]]
 747        })
 748    }
 749
 750    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 751        let assist = &self.assists[&assist_id];
 752        let Some(decorations) = assist.decorations.as_ref() else {
 753            return;
 754        };
 755        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 756        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 757
 758        assist_group.active_assist_id = Some(assist_id);
 759        if assist_group.linked {
 760            for assist_id in &assist_group.assist_ids {
 761                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 762                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 763                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 764                    });
 765                }
 766            }
 767        }
 768
 769        assist
 770            .editor
 771            .update(cx, |editor, cx| {
 772                let scroll_top = editor.scroll_position(cx).y;
 773                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 774                editor_assists.scroll_lock = editor
 775                    .row_for_block(decorations.prompt_block_id, cx)
 776                    .map(|row| row.as_f64())
 777                    .filter(|prompt_row| (scroll_top..scroll_bottom).contains(&prompt_row))
 778                    .map(|prompt_row| InlineAssistScrollLock {
 779                        assist_id,
 780                        distance_from_top: prompt_row - scroll_top,
 781                    });
 782            })
 783            .ok();
 784    }
 785
 786    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 787        let assist = &self.assists[&assist_id];
 788        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 789        if assist_group.active_assist_id == Some(assist_id) {
 790            assist_group.active_assist_id = None;
 791            if assist_group.linked {
 792                for assist_id in &assist_group.assist_ids {
 793                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 794                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 795                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 796                        });
 797                    }
 798                }
 799            }
 800        }
 801    }
 802
 803    fn handle_prompt_editor_event(
 804        &mut self,
 805        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 806        event: &PromptEditorEvent,
 807        window: &mut Window,
 808        cx: &mut App,
 809    ) {
 810        let assist_id = prompt_editor.read(cx).id();
 811        match event {
 812            PromptEditorEvent::StartRequested => {
 813                self.start_assist(assist_id, window, cx);
 814            }
 815            PromptEditorEvent::StopRequested => {
 816                self.stop_assist(assist_id, cx);
 817            }
 818            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 819                self.finish_assist(assist_id, false, window, cx);
 820            }
 821            PromptEditorEvent::CancelRequested => {
 822                self.finish_assist(assist_id, true, window, cx);
 823            }
 824            PromptEditorEvent::Resized { .. } => {
 825                // This only matters for the terminal inline assistant
 826            }
 827        }
 828    }
 829
 830    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 831        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 832            return;
 833        };
 834
 835        if editor.read(cx).selections.count() == 1 {
 836            let (selection, buffer) = editor.update(cx, |editor, cx| {
 837                (
 838                    editor
 839                        .selections
 840                        .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
 841                    editor.buffer().read(cx).snapshot(cx),
 842                )
 843            });
 844            for assist_id in &editor_assists.assist_ids {
 845                let assist = &self.assists[assist_id];
 846                let assist_range = assist.range.to_offset(&buffer);
 847                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 848                {
 849                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 850                        self.dismiss_assist(*assist_id, window, cx);
 851                    } else {
 852                        self.finish_assist(*assist_id, false, window, cx);
 853                    }
 854
 855                    return;
 856                }
 857            }
 858        }
 859
 860        cx.propagate();
 861    }
 862
 863    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 864        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 865            return;
 866        };
 867
 868        if editor.read(cx).selections.count() == 1 {
 869            let (selection, buffer) = editor.update(cx, |editor, cx| {
 870                (
 871                    editor
 872                        .selections
 873                        .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
 874                    editor.buffer().read(cx).snapshot(cx),
 875                )
 876            });
 877            let mut closest_assist_fallback = None;
 878            for assist_id in &editor_assists.assist_ids {
 879                let assist = &self.assists[assist_id];
 880                let assist_range = assist.range.to_offset(&buffer);
 881                if assist.decorations.is_some() {
 882                    if assist_range.contains(&selection.start)
 883                        && assist_range.contains(&selection.end)
 884                    {
 885                        self.focus_assist(*assist_id, window, cx);
 886                        return;
 887                    } else {
 888                        let distance_from_selection = assist_range
 889                            .start
 890                            .0
 891                            .abs_diff(selection.start.0)
 892                            .min(assist_range.start.0.abs_diff(selection.end.0))
 893                            + assist_range
 894                                .end
 895                                .0
 896                                .abs_diff(selection.start.0)
 897                                .min(assist_range.end.0.abs_diff(selection.end.0));
 898                        match closest_assist_fallback {
 899                            Some((_, old_distance)) => {
 900                                if distance_from_selection < old_distance {
 901                                    closest_assist_fallback =
 902                                        Some((assist_id, distance_from_selection));
 903                                }
 904                            }
 905                            None => {
 906                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 907                            }
 908                        }
 909                    }
 910                }
 911            }
 912
 913            if let Some((&assist_id, _)) = closest_assist_fallback {
 914                self.focus_assist(assist_id, window, cx);
 915            }
 916        }
 917
 918        cx.propagate();
 919    }
 920
 921    fn handle_editor_release(
 922        &mut self,
 923        editor: WeakEntity<Editor>,
 924        window: &mut Window,
 925        cx: &mut App,
 926    ) {
 927        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 928            for assist_id in editor_assists.assist_ids.clone() {
 929                self.finish_assist(assist_id, true, window, cx);
 930            }
 931        }
 932    }
 933
 934    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 935        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 936            return;
 937        };
 938        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 939            return;
 940        };
 941        let assist = &self.assists[&scroll_lock.assist_id];
 942        let Some(decorations) = assist.decorations.as_ref() else {
 943            return;
 944        };
 945
 946        editor.update(cx, |editor, cx| {
 947            let scroll_position = editor.scroll_position(cx);
 948            let target_scroll_top = editor
 949                .row_for_block(decorations.prompt_block_id, cx)?
 950                .as_f64()
 951                - scroll_lock.distance_from_top;
 952            if target_scroll_top != scroll_position.y {
 953                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 954            }
 955            Some(())
 956        });
 957    }
 958
 959    fn handle_editor_event(
 960        &mut self,
 961        editor: Entity<Editor>,
 962        event: &EditorEvent,
 963        window: &mut Window,
 964        cx: &mut App,
 965    ) {
 966        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 967            return;
 968        };
 969
 970        match event {
 971            EditorEvent::Edited { transaction_id } => {
 972                let buffer = editor.read(cx).buffer().read(cx);
 973                let edited_ranges =
 974                    buffer.edited_ranges_for_transaction::<MultiBufferOffset>(*transaction_id, cx);
 975                let snapshot = buffer.snapshot(cx);
 976
 977                for assist_id in editor_assists.assist_ids.clone() {
 978                    let assist = &self.assists[&assist_id];
 979                    if matches!(
 980                        assist.codegen.read(cx).status(cx),
 981                        CodegenStatus::Error(_) | CodegenStatus::Done
 982                    ) {
 983                        let assist_range = assist.range.to_offset(&snapshot);
 984                        if edited_ranges
 985                            .iter()
 986                            .any(|range| range.overlaps(&assist_range))
 987                        {
 988                            self.finish_assist(assist_id, false, window, cx);
 989                        }
 990                    }
 991                }
 992            }
 993            EditorEvent::ScrollPositionChanged { .. } => {
 994                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 995                    let assist = &self.assists[&scroll_lock.assist_id];
 996                    if let Some(decorations) = assist.decorations.as_ref() {
 997                        let distance_from_top = editor.update(cx, |editor, cx| {
 998                            let scroll_top = editor.scroll_position(cx).y;
 999                            let prompt_row = editor
1000                                .row_for_block(decorations.prompt_block_id, cx)?
1001                                .0 as ScrollOffset;
1002                            Some(prompt_row - scroll_top)
1003                        });
1004
1005                        if distance_from_top.is_none_or(|distance_from_top| {
1006                            distance_from_top != scroll_lock.distance_from_top
1007                        }) {
1008                            editor_assists.scroll_lock = None;
1009                        }
1010                    }
1011                }
1012            }
1013            EditorEvent::SelectionsChanged { .. } => {
1014                for assist_id in editor_assists.assist_ids.clone() {
1015                    let assist = &self.assists[&assist_id];
1016                    if let Some(decorations) = assist.decorations.as_ref()
1017                        && decorations
1018                            .prompt_editor
1019                            .focus_handle(cx)
1020                            .is_focused(window)
1021                    {
1022                        return;
1023                    }
1024                }
1025
1026                editor_assists.scroll_lock = None;
1027            }
1028            _ => {}
1029        }
1030    }
1031
1032    pub fn finish_assist(
1033        &mut self,
1034        assist_id: InlineAssistId,
1035        undo: bool,
1036        window: &mut Window,
1037        cx: &mut App,
1038    ) {
1039        if let Some(assist) = self.assists.get(&assist_id) {
1040            let assist_group_id = assist.group_id;
1041            if self.assist_groups[&assist_group_id].linked {
1042                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1043                    self.finish_assist(assist_id, undo, window, cx);
1044                }
1045                return;
1046            }
1047        }
1048
1049        self.dismiss_assist(assist_id, window, cx);
1050
1051        if let Some(assist) = self.assists.remove(&assist_id) {
1052            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
1053            {
1054                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1055                if entry.get().assist_ids.is_empty() {
1056                    entry.remove();
1057                }
1058            }
1059
1060            if let hash_map::Entry::Occupied(mut entry) =
1061                self.assists_by_editor.entry(assist.editor.clone())
1062            {
1063                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1064                if entry.get().assist_ids.is_empty() {
1065                    entry.remove();
1066                    if let Some(editor) = assist.editor.upgrade() {
1067                        self.update_editor_highlights(&editor, cx);
1068                    }
1069                } else {
1070                    entry.get_mut().highlight_updates.send(()).ok();
1071                }
1072            }
1073
1074            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1075            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1076                let language_name = assist.editor.upgrade().and_then(|editor| {
1077                    let multibuffer = editor.read(cx).buffer().read(cx);
1078                    let snapshot = multibuffer.snapshot(cx);
1079                    let ranges =
1080                        snapshot.range_to_buffer_ranges(assist.range.start..=assist.range.end);
1081                    ranges
1082                        .first()
1083                        .and_then(|(buffer, _, _)| buffer.language())
1084                        .map(|language| language.name().0.to_string())
1085                });
1086
1087                let codegen = assist.codegen.read(cx);
1088                let session_id = codegen.session_id();
1089                let message_id = active_alternative.read(cx).message_id.clone();
1090                let model_telemetry_id = model.model.telemetry_id();
1091                let model_provider_id = model.model.provider_id().to_string();
1092
1093                let (phase, event_type, anthropic_event_type) = if undo {
1094                    (
1095                        "rejected",
1096                        "Assistant Response Rejected",
1097                        language_model::AnthropicEventType::Reject,
1098                    )
1099                } else {
1100                    (
1101                        "accepted",
1102                        "Assistant Response Accepted",
1103                        language_model::AnthropicEventType::Accept,
1104                    )
1105                };
1106
1107                telemetry::event!(
1108                    event_type,
1109                    phase,
1110                    session_id = session_id.to_string(),
1111                    kind = "inline",
1112                    model = model_telemetry_id,
1113                    model_provider = model_provider_id,
1114                    language_name = language_name,
1115                    message_id = message_id.as_deref(),
1116                );
1117
1118                report_anthropic_event(
1119                    &model.model,
1120                    language_model::AnthropicEventData {
1121                        completion_type: language_model::AnthropicCompletionType::Editor,
1122                        event: anthropic_event_type,
1123                        language_name,
1124                        message_id,
1125                    },
1126                    cx,
1127                );
1128            }
1129
1130            if undo {
1131                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1132            } else {
1133                self.confirmed_assists.insert(assist_id, active_alternative);
1134            }
1135        }
1136    }
1137
1138    fn dismiss_assist(
1139        &mut self,
1140        assist_id: InlineAssistId,
1141        window: &mut Window,
1142        cx: &mut App,
1143    ) -> bool {
1144        let Some(assist) = self.assists.get_mut(&assist_id) else {
1145            return false;
1146        };
1147        let Some(editor) = assist.editor.upgrade() else {
1148            return false;
1149        };
1150        let Some(decorations) = assist.decorations.take() else {
1151            return false;
1152        };
1153
1154        editor.update(cx, |editor, cx| {
1155            let mut to_remove = decorations.removed_line_block_ids;
1156            to_remove.insert(decorations.prompt_block_id);
1157            to_remove.insert(decorations.end_block_id);
1158            if let Some(tool_description_block_id) = decorations.model_explanation {
1159                to_remove.insert(tool_description_block_id);
1160            }
1161            editor.remove_blocks(to_remove, None, cx);
1162        });
1163
1164        if decorations
1165            .prompt_editor
1166            .focus_handle(cx)
1167            .contains_focused(window, cx)
1168        {
1169            self.focus_next_assist(assist_id, window, cx);
1170        }
1171
1172        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1173            if editor_assists
1174                .scroll_lock
1175                .as_ref()
1176                .is_some_and(|lock| lock.assist_id == assist_id)
1177            {
1178                editor_assists.scroll_lock = None;
1179            }
1180            editor_assists.highlight_updates.send(()).ok();
1181        }
1182
1183        true
1184    }
1185
1186    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1187        let Some(assist) = self.assists.get(&assist_id) else {
1188            return;
1189        };
1190
1191        let assist_group = &self.assist_groups[&assist.group_id];
1192        let assist_ix = assist_group
1193            .assist_ids
1194            .iter()
1195            .position(|id| *id == assist_id)
1196            .unwrap();
1197        let assist_ids = assist_group
1198            .assist_ids
1199            .iter()
1200            .skip(assist_ix + 1)
1201            .chain(assist_group.assist_ids.iter().take(assist_ix));
1202
1203        for assist_id in assist_ids {
1204            let assist = &self.assists[assist_id];
1205            if assist.decorations.is_some() {
1206                self.focus_assist(*assist_id, window, cx);
1207                return;
1208            }
1209        }
1210
1211        assist
1212            .editor
1213            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
1214            .ok();
1215    }
1216
1217    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1218        let Some(assist) = self.assists.get(&assist_id) else {
1219            return;
1220        };
1221
1222        if let Some(decorations) = assist.decorations.as_ref() {
1223            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1224                prompt_editor.editor.update(cx, |editor, cx| {
1225                    window.focus(&editor.focus_handle(cx), cx);
1226                    editor.select_all(&SelectAll, window, cx);
1227                })
1228            });
1229        }
1230
1231        self.scroll_to_assist(assist_id, window, cx);
1232    }
1233
1234    pub fn scroll_to_assist(
1235        &mut self,
1236        assist_id: InlineAssistId,
1237        window: &mut Window,
1238        cx: &mut App,
1239    ) {
1240        let Some(assist) = self.assists.get(&assist_id) else {
1241            return;
1242        };
1243        let Some(editor) = assist.editor.upgrade() else {
1244            return;
1245        };
1246
1247        let position = assist.range.start;
1248        editor.update(cx, |editor, cx| {
1249            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1250                selections.select_anchor_ranges([position..position])
1251            });
1252
1253            let mut scroll_target_range = None;
1254            if let Some(decorations) = assist.decorations.as_ref() {
1255                scroll_target_range = maybe!({
1256                    let top = editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f64;
1257                    let bottom = editor.row_for_block(decorations.end_block_id, cx)?.0 as f64;
1258                    Some((top, bottom))
1259                });
1260                if scroll_target_range.is_none() {
1261                    log::error!("bug: failed to find blocks for scrolling to inline assist");
1262                }
1263            }
1264            let scroll_target_range = scroll_target_range.unwrap_or_else(|| {
1265                let snapshot = editor.snapshot(window, cx);
1266                let start_row = assist
1267                    .range
1268                    .start
1269                    .to_display_point(&snapshot.display_snapshot)
1270                    .row();
1271                let top = start_row.0 as ScrollOffset;
1272                let bottom = top + 1.0;
1273                (top, bottom)
1274            });
1275            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1276            let vertical_scroll_margin = editor.vertical_scroll_margin() as ScrollOffset;
1277            let scroll_target_top = (scroll_target_range.0 - vertical_scroll_margin)
1278                // Don't scroll up too far in the case of a large vertical_scroll_margin.
1279                .max(scroll_target_range.0 - height_in_lines / 2.0);
1280            let scroll_target_bottom = (scroll_target_range.1 + vertical_scroll_margin)
1281                // Don't scroll down past where the top would still be visible.
1282                .min(scroll_target_top + height_in_lines);
1283
1284            let scroll_top = editor.scroll_position(cx).y;
1285            let scroll_bottom = scroll_top + height_in_lines;
1286
1287            if scroll_target_top < scroll_top {
1288                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1289            } else if scroll_target_bottom > scroll_bottom {
1290                editor.set_scroll_position(
1291                    point(0., scroll_target_bottom - height_in_lines),
1292                    window,
1293                    cx,
1294                );
1295            }
1296        });
1297    }
1298
1299    fn unlink_assist_group(
1300        &mut self,
1301        assist_group_id: InlineAssistGroupId,
1302        window: &mut Window,
1303        cx: &mut App,
1304    ) -> Vec<InlineAssistId> {
1305        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1306        assist_group.linked = false;
1307
1308        for assist_id in &assist_group.assist_ids {
1309            let assist = self.assists.get_mut(assist_id).unwrap();
1310            if let Some(editor_decorations) = assist.decorations.as_ref() {
1311                editor_decorations
1312                    .prompt_editor
1313                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1314            }
1315        }
1316        assist_group.assist_ids.clone()
1317    }
1318
1319    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1320        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1321            assist
1322        } else {
1323            return;
1324        };
1325
1326        let assist_group_id = assist.group_id;
1327        if self.assist_groups[&assist_group_id].linked {
1328            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1329                self.start_assist(assist_id, window, cx);
1330            }
1331            return;
1332        }
1333
1334        let Some((user_prompt, mention_set)) = assist.user_prompt(cx).zip(assist.mention_set(cx))
1335        else {
1336            return;
1337        };
1338
1339        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1340        self.prompt_history.push_back(user_prompt.clone());
1341        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1342            self.prompt_history.pop_front();
1343        }
1344
1345        let Some(ConfiguredModel { model, .. }) =
1346            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1347        else {
1348            return;
1349        };
1350
1351        let context_task = load_context(&mention_set, cx).shared();
1352        assist
1353            .codegen
1354            .update(cx, |codegen, cx| {
1355                codegen.start(model, user_prompt, context_task, cx)
1356            })
1357            .log_err();
1358    }
1359
1360    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1361        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1362            assist
1363        } else {
1364            return;
1365        };
1366
1367        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1368    }
1369
1370    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1371        let mut gutter_pending_ranges = Vec::new();
1372        let mut gutter_transformed_ranges = Vec::new();
1373        let mut foreground_ranges = Vec::new();
1374        let mut inserted_row_ranges = Vec::new();
1375        let empty_assist_ids = Vec::new();
1376        let assist_ids = self
1377            .assists_by_editor
1378            .get(&editor.downgrade())
1379            .map_or(&empty_assist_ids, |editor_assists| {
1380                &editor_assists.assist_ids
1381            });
1382
1383        for assist_id in assist_ids {
1384            if let Some(assist) = self.assists.get(assist_id) {
1385                let codegen = assist.codegen.read(cx);
1386                let buffer = codegen.buffer(cx).read(cx).read(cx);
1387                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1388
1389                let pending_range =
1390                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1391                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1392                    gutter_pending_ranges.push(pending_range);
1393                }
1394
1395                if let Some(edit_position) = codegen.edit_position(cx) {
1396                    let edited_range = assist.range.start..edit_position;
1397                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1398                        gutter_transformed_ranges.push(edited_range);
1399                    }
1400                }
1401
1402                if assist.decorations.is_some() {
1403                    inserted_row_ranges
1404                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1405                }
1406            }
1407        }
1408
1409        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1410        merge_ranges(&mut foreground_ranges, &snapshot);
1411        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1412        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1413        editor.update(cx, |editor, cx| {
1414            enum GutterPendingRange {}
1415            if gutter_pending_ranges.is_empty() {
1416                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1417            } else {
1418                editor.highlight_gutter::<GutterPendingRange>(
1419                    gutter_pending_ranges,
1420                    |cx| cx.theme().status().info_background,
1421                    cx,
1422                )
1423            }
1424
1425            enum GutterTransformedRange {}
1426            if gutter_transformed_ranges.is_empty() {
1427                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1428            } else {
1429                editor.highlight_gutter::<GutterTransformedRange>(
1430                    gutter_transformed_ranges,
1431                    |cx| cx.theme().status().info,
1432                    cx,
1433                )
1434            }
1435
1436            if foreground_ranges.is_empty() {
1437                editor.clear_highlights(HighlightKey::InlineAssist, cx);
1438            } else {
1439                editor.highlight_text(
1440                    HighlightKey::InlineAssist,
1441                    foreground_ranges,
1442                    HighlightStyle {
1443                        fade_out: Some(0.6),
1444                        ..Default::default()
1445                    },
1446                    cx,
1447                );
1448            }
1449
1450            editor.clear_row_highlights::<InlineAssist>();
1451            for row_range in inserted_row_ranges {
1452                editor.highlight_rows::<InlineAssist>(
1453                    row_range,
1454                    cx.theme().status().info_background,
1455                    Default::default(),
1456                    cx,
1457                );
1458            }
1459        });
1460    }
1461
1462    fn update_editor_blocks(
1463        &mut self,
1464        editor: &Entity<Editor>,
1465        assist_id: InlineAssistId,
1466        window: &mut Window,
1467        cx: &mut App,
1468    ) {
1469        let Some(assist) = self.assists.get_mut(&assist_id) else {
1470            return;
1471        };
1472        let Some(decorations) = assist.decorations.as_mut() else {
1473            return;
1474        };
1475
1476        let codegen = assist.codegen.read(cx);
1477        let old_snapshot = codegen.snapshot(cx);
1478        let old_buffer = codegen.old_buffer(cx);
1479        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1480
1481        editor.update(cx, |editor, cx| {
1482            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1483            editor.remove_blocks(old_blocks, None, cx);
1484
1485            let mut new_blocks = Vec::new();
1486            for (new_row, old_row_range) in deleted_row_ranges {
1487                let (_, buffer_start) = old_snapshot
1488                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1489                    .unwrap();
1490                let (_, buffer_end) = old_snapshot
1491                    .point_to_buffer_offset(Point::new(
1492                        *old_row_range.end(),
1493                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1494                    ))
1495                    .unwrap();
1496
1497                let deleted_lines_editor = cx.new(|cx| {
1498                    let multi_buffer =
1499                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1500                    multi_buffer.update(cx, |multi_buffer, cx| {
1501                        multi_buffer.push_excerpts(
1502                            old_buffer.clone(),
1503                            // todo(lw): buffer_start and buffer_end might come from different snapshots!
1504                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1505                            cx,
1506                        );
1507                    });
1508
1509                    enum DeletedLines {}
1510                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1511                    editor.disable_scrollbars_and_minimap(window, cx);
1512                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1513                    editor.set_show_wrap_guides(false, cx);
1514                    editor.set_show_gutter(false, cx);
1515                    editor.set_offset_content(false, cx);
1516                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1517                    editor.set_read_only(true);
1518                    editor.set_show_edit_predictions(Some(false), window, cx);
1519                    editor.highlight_rows::<DeletedLines>(
1520                        Anchor::min()..Anchor::max(),
1521                        cx.theme().status().deleted_background,
1522                        Default::default(),
1523                        cx,
1524                    );
1525                    editor
1526                });
1527
1528                let height =
1529                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1530                new_blocks.push(BlockProperties {
1531                    placement: BlockPlacement::Above(new_row),
1532                    height: Some(height),
1533                    style: BlockStyle::Flex,
1534                    render: Arc::new(move |cx| {
1535                        div()
1536                            .block_mouse_except_scroll()
1537                            .bg(cx.theme().status().deleted_background)
1538                            .size_full()
1539                            .h(height as f32 * cx.window.line_height())
1540                            .pl(cx.margins.gutter.full_width())
1541                            .child(deleted_lines_editor.clone())
1542                            .into_any_element()
1543                    }),
1544                    priority: 0,
1545                });
1546            }
1547
1548            decorations.removed_line_block_ids = editor
1549                .insert_blocks(new_blocks, None, cx)
1550                .into_iter()
1551                .collect();
1552        })
1553    }
1554
1555    fn resolve_inline_assist_target(
1556        workspace: &mut Workspace,
1557        agent_panel: Option<Entity<AgentPanel>>,
1558        window: &mut Window,
1559        cx: &mut App,
1560    ) -> Option<InlineAssistTarget> {
1561        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx)
1562            && terminal_panel
1563                .read(cx)
1564                .focus_handle(cx)
1565                .contains_focused(window, cx)
1566            && let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1567                pane.read(cx)
1568                    .active_item()
1569                    .and_then(|t| t.downcast::<TerminalView>())
1570            })
1571        {
1572            return Some(InlineAssistTarget::Terminal(terminal_view));
1573        }
1574
1575        let text_thread_editor = agent_panel
1576            .and_then(|panel| panel.read(cx).active_text_thread_editor())
1577            .and_then(|editor| {
1578                let editor = &editor.read(cx).editor().clone();
1579                if editor.read(cx).is_focused(window) {
1580                    Some(editor.clone())
1581                } else {
1582                    None
1583                }
1584            });
1585
1586        if let Some(text_thread_editor) = text_thread_editor {
1587            Some(InlineAssistTarget::Editor(text_thread_editor))
1588        } else if let Some(workspace_editor) = workspace
1589            .active_item(cx)
1590            .and_then(|item| item.act_as::<Editor>(cx))
1591        {
1592            Some(InlineAssistTarget::Editor(workspace_editor))
1593        } else {
1594            workspace
1595                .active_item(cx)
1596                .and_then(|item| item.act_as::<TerminalView>(cx))
1597                .map(InlineAssistTarget::Terminal)
1598        }
1599    }
1600
1601    #[cfg(any(test, feature = "test-support"))]
1602    pub fn set_completion_receiver(
1603        &mut self,
1604        sender: mpsc::UnboundedSender<anyhow::Result<InlineAssistId>>,
1605    ) {
1606        self._inline_assistant_completions = Some(sender);
1607    }
1608
1609    #[cfg(any(test, feature = "test-support"))]
1610    pub fn get_codegen(
1611        &mut self,
1612        assist_id: InlineAssistId,
1613        cx: &mut App,
1614    ) -> Option<Entity<CodegenAlternative>> {
1615        self.assists.get(&assist_id).map(|inline_assist| {
1616            inline_assist
1617                .codegen
1618                .update(cx, |codegen, _cx| codegen.active_alternative().clone())
1619        })
1620    }
1621}
1622
1623struct EditorInlineAssists {
1624    assist_ids: Vec<InlineAssistId>,
1625    scroll_lock: Option<InlineAssistScrollLock>,
1626    highlight_updates: watch::Sender<()>,
1627    _update_highlights: Task<Result<()>>,
1628    _subscriptions: Vec<gpui::Subscription>,
1629}
1630
1631struct InlineAssistScrollLock {
1632    assist_id: InlineAssistId,
1633    distance_from_top: ScrollOffset,
1634}
1635
1636impl EditorInlineAssists {
1637    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1638        let (highlight_updates_tx, mut highlight_updates_rx) = watch::channel(());
1639        Self {
1640            assist_ids: Vec::new(),
1641            scroll_lock: None,
1642            highlight_updates: highlight_updates_tx,
1643            _update_highlights: cx.spawn({
1644                let editor = editor.downgrade();
1645                async move |cx| {
1646                    while let Ok(()) = highlight_updates_rx.changed().await {
1647                        let editor = editor.upgrade().context("editor was dropped")?;
1648                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1649                            assistant.update_editor_highlights(&editor, cx);
1650                        });
1651                    }
1652                    Ok(())
1653                }
1654            }),
1655            _subscriptions: vec![
1656                cx.observe_release_in(editor, window, {
1657                    let editor = editor.downgrade();
1658                    |_, window, cx| {
1659                        InlineAssistant::update_global(cx, |this, cx| {
1660                            this.handle_editor_release(editor, window, cx);
1661                        })
1662                    }
1663                }),
1664                window.observe(editor, cx, move |editor, window, cx| {
1665                    InlineAssistant::update_global(cx, |this, cx| {
1666                        this.handle_editor_change(editor, window, cx)
1667                    })
1668                }),
1669                window.subscribe(editor, cx, move |editor, event, window, cx| {
1670                    InlineAssistant::update_global(cx, |this, cx| {
1671                        this.handle_editor_event(editor, event, window, cx)
1672                    })
1673                }),
1674                editor.update(cx, |editor, cx| {
1675                    let editor_handle = cx.entity().downgrade();
1676                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1677                        InlineAssistant::update_global(cx, |this, cx| {
1678                            if let Some(editor) = editor_handle.upgrade() {
1679                                this.handle_editor_newline(editor, window, cx)
1680                            }
1681                        })
1682                    })
1683                }),
1684                editor.update(cx, |editor, cx| {
1685                    let editor_handle = cx.entity().downgrade();
1686                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1687                        InlineAssistant::update_global(cx, |this, cx| {
1688                            if let Some(editor) = editor_handle.upgrade() {
1689                                this.handle_editor_cancel(editor, window, cx)
1690                            }
1691                        })
1692                    })
1693                }),
1694            ],
1695        }
1696    }
1697}
1698
1699struct InlineAssistGroup {
1700    assist_ids: Vec<InlineAssistId>,
1701    linked: bool,
1702    active_assist_id: Option<InlineAssistId>,
1703}
1704
1705impl InlineAssistGroup {
1706    fn new() -> Self {
1707        Self {
1708            assist_ids: Vec::new(),
1709            linked: true,
1710            active_assist_id: None,
1711        }
1712    }
1713}
1714
1715fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1716    let editor = editor.clone();
1717
1718    Arc::new(move |cx: &mut BlockContext| {
1719        let editor_margins = editor.read(cx).editor_margins();
1720
1721        *editor_margins.lock() = *cx.margins;
1722        editor.clone().into_any_element()
1723    })
1724}
1725
1726#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1727struct InlineAssistGroupId(usize);
1728
1729impl InlineAssistGroupId {
1730    fn post_inc(&mut self) -> InlineAssistGroupId {
1731        let id = *self;
1732        self.0 += 1;
1733        id
1734    }
1735}
1736
1737pub struct InlineAssist {
1738    group_id: InlineAssistGroupId,
1739    range: Range<Anchor>,
1740    editor: WeakEntity<Editor>,
1741    decorations: Option<InlineAssistDecorations>,
1742    codegen: Entity<BufferCodegen>,
1743    _subscriptions: Vec<Subscription>,
1744    workspace: WeakEntity<Workspace>,
1745}
1746
1747impl InlineAssist {
1748    fn new(
1749        assist_id: InlineAssistId,
1750        group_id: InlineAssistGroupId,
1751        editor: &Entity<Editor>,
1752        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1753        prompt_block_id: CustomBlockId,
1754        tool_description_block_id: CustomBlockId,
1755        end_block_id: CustomBlockId,
1756        range: Range<Anchor>,
1757        codegen: Entity<BufferCodegen>,
1758        workspace: WeakEntity<Workspace>,
1759        window: &mut Window,
1760        cx: &mut App,
1761    ) -> Self {
1762        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1763        InlineAssist {
1764            group_id,
1765            editor: editor.downgrade(),
1766            decorations: Some(InlineAssistDecorations {
1767                prompt_block_id,
1768                prompt_editor: prompt_editor.clone(),
1769                removed_line_block_ids: Default::default(),
1770                model_explanation: Some(tool_description_block_id),
1771                end_block_id,
1772            }),
1773            range,
1774            codegen: codegen.clone(),
1775            workspace,
1776            _subscriptions: vec![
1777                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1778                    InlineAssistant::update_global(cx, |this, cx| {
1779                        this.handle_prompt_editor_focus_in(assist_id, cx)
1780                    })
1781                }),
1782                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1783                    InlineAssistant::update_global(cx, |this, cx| {
1784                        this.handle_prompt_editor_focus_out(assist_id, cx)
1785                    })
1786                }),
1787                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1788                    InlineAssistant::update_global(cx, |this, cx| {
1789                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1790                    })
1791                }),
1792                window.observe(&codegen, cx, {
1793                    let editor = editor.downgrade();
1794                    move |_, window, cx| {
1795                        if let Some(editor) = editor.upgrade() {
1796                            InlineAssistant::update_global(cx, |this, cx| {
1797                                if let Some(editor_assists) =
1798                                    this.assists_by_editor.get_mut(&editor.downgrade())
1799                                {
1800                                    editor_assists.highlight_updates.send(()).ok();
1801                                }
1802
1803                                this.update_editor_blocks(&editor, assist_id, window, cx);
1804                            })
1805                        }
1806                    }
1807                }),
1808                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1809                    InlineAssistant::update_global(cx, |this, cx| match event {
1810                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1811                        CodegenEvent::Finished => {
1812                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1813                                assist
1814                            } else {
1815                                return;
1816                            };
1817
1818                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx)
1819                                && assist.decorations.is_none()
1820                                && let Some(workspace) = assist.workspace.upgrade()
1821                            {
1822                                #[cfg(any(test, feature = "test-support"))]
1823                                if let Some(sender) = &mut this._inline_assistant_completions {
1824                                    sender
1825                                        .unbounded_send(Err(anyhow::anyhow!(
1826                                            "Inline assistant error: {}",
1827                                            error
1828                                        )))
1829                                        .ok();
1830                                }
1831
1832                                let error = format!("Inline assistant error: {}", error);
1833                                workspace.update(cx, |workspace, cx| {
1834                                    struct InlineAssistantError;
1835
1836                                    let id = NotificationId::composite::<InlineAssistantError>(
1837                                        assist_id.0,
1838                                    );
1839
1840                                    workspace.show_toast(
1841                                        Toast::new(id, error),
1842                                        NotificationSource::Agent,
1843                                        cx,
1844                                    );
1845                                })
1846                            } else {
1847                                #[cfg(any(test, feature = "test-support"))]
1848                                if let Some(sender) = &mut this._inline_assistant_completions {
1849                                    sender.unbounded_send(Ok(assist_id)).ok();
1850                                }
1851                            }
1852
1853                            if assist.decorations.is_none() {
1854                                this.finish_assist(assist_id, false, window, cx);
1855                            }
1856                        }
1857                    })
1858                }),
1859            ],
1860        }
1861    }
1862
1863    fn user_prompt(&self, cx: &App) -> Option<String> {
1864        let decorations = self.decorations.as_ref()?;
1865        Some(decorations.prompt_editor.read(cx).prompt(cx))
1866    }
1867
1868    fn mention_set(&self, cx: &App) -> Option<Entity<MentionSet>> {
1869        let decorations = self.decorations.as_ref()?;
1870        Some(decorations.prompt_editor.read(cx).mention_set().clone())
1871    }
1872}
1873
1874struct InlineAssistDecorations {
1875    prompt_block_id: CustomBlockId,
1876    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1877    removed_line_block_ids: HashSet<CustomBlockId>,
1878    model_explanation: Option<CustomBlockId>,
1879    end_block_id: CustomBlockId,
1880}
1881
1882struct AssistantCodeActionProvider {
1883    editor: WeakEntity<Editor>,
1884    workspace: WeakEntity<Workspace>,
1885}
1886
1887const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant";
1888
1889impl CodeActionProvider for AssistantCodeActionProvider {
1890    fn id(&self) -> Arc<str> {
1891        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1892    }
1893
1894    fn code_actions(
1895        &self,
1896        buffer: &Entity<Buffer>,
1897        range: Range<text::Anchor>,
1898        _: &mut Window,
1899        cx: &mut App,
1900    ) -> Task<Result<Vec<CodeAction>>> {
1901        if !AgentSettings::get_global(cx).enabled(cx) {
1902            return Task::ready(Ok(Vec::new()));
1903        }
1904
1905        let snapshot = buffer.read(cx).snapshot();
1906        let mut range = range.to_point(&snapshot);
1907
1908        // Expand the range to line boundaries.
1909        range.start.column = 0;
1910        range.end.column = snapshot.line_len(range.end.row);
1911
1912        let mut has_diagnostics = false;
1913        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1914            range.start = cmp::min(range.start, diagnostic.range.start);
1915            range.end = cmp::max(range.end, diagnostic.range.end);
1916            has_diagnostics = true;
1917        }
1918        if has_diagnostics {
1919            let symbols_containing_start = snapshot.symbols_containing(range.start, None);
1920            if let Some(symbol) = symbols_containing_start.last() {
1921                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1922                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1923            }
1924            let symbols_containing_end = snapshot.symbols_containing(range.end, None);
1925            if let Some(symbol) = symbols_containing_end.last() {
1926                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1927                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1928            }
1929
1930            Task::ready(Ok(vec![CodeAction {
1931                server_id: language::LanguageServerId(0),
1932                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1933                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1934                    title: "Fix with Assistant".into(),
1935                    ..Default::default()
1936                })),
1937                resolved: true,
1938            }]))
1939        } else {
1940            Task::ready(Ok(Vec::new()))
1941        }
1942    }
1943
1944    fn apply_code_action(
1945        &self,
1946        buffer: Entity<Buffer>,
1947        action: CodeAction,
1948        excerpt_id: ExcerptId,
1949        _push_to_history: bool,
1950        window: &mut Window,
1951        cx: &mut App,
1952    ) -> Task<Result<ProjectTransaction>> {
1953        let editor = self.editor.clone();
1954        let workspace = self.workspace.clone();
1955        let prompt_store = PromptStore::global(cx);
1956        window.spawn(cx, async move |cx| {
1957            let workspace = workspace.upgrade().context("workspace was released")?;
1958            let (thread_store, history) = cx.update(|_window, cx| {
1959                let panel = workspace
1960                    .read(cx)
1961                    .panel::<AgentPanel>(cx)
1962                    .context("missing agent panel")?
1963                    .read(cx);
1964                anyhow::Ok((panel.thread_store().clone(), panel.history().downgrade()))
1965            })??;
1966            let editor = editor.upgrade().context("editor was released")?;
1967            let range = editor
1968                .update(cx, |editor, cx| {
1969                    editor.buffer().update(cx, |multibuffer, cx| {
1970                        let buffer = buffer.read(cx);
1971                        let multibuffer_snapshot = multibuffer.read(cx);
1972
1973                        let old_context_range =
1974                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1975                        let mut new_context_range = old_context_range.clone();
1976                        if action
1977                            .range
1978                            .start
1979                            .cmp(&old_context_range.start, buffer)
1980                            .is_lt()
1981                        {
1982                            new_context_range.start = action.range.start;
1983                        }
1984                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1985                            new_context_range.end = action.range.end;
1986                        }
1987                        drop(multibuffer_snapshot);
1988
1989                        if new_context_range != old_context_range {
1990                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1991                        }
1992
1993                        let multibuffer_snapshot = multibuffer.read(cx);
1994                        multibuffer_snapshot.anchor_range_in_excerpt(excerpt_id, action.range)
1995                    })
1996                })
1997                .context("invalid range")?;
1998
1999            let prompt_store = prompt_store.await.ok();
2000            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
2001                let assist_id = assistant.suggest_assist(
2002                    &editor,
2003                    range,
2004                    "Fix Diagnostics".into(),
2005                    None,
2006                    true,
2007                    workspace,
2008                    thread_store,
2009                    prompt_store,
2010                    history,
2011                    window,
2012                    cx,
2013                );
2014                assistant.start_assist(assist_id, window, cx);
2015            })?;
2016
2017            Ok(ProjectTransaction::default())
2018        })
2019    }
2020}
2021
2022fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
2023    ranges.sort_unstable_by(|a, b| {
2024        a.start
2025            .cmp(&b.start, buffer)
2026            .then_with(|| b.end.cmp(&a.end, buffer))
2027    });
2028
2029    let mut ix = 0;
2030    while ix + 1 < ranges.len() {
2031        let b = ranges[ix + 1].clone();
2032        let a = &mut ranges[ix];
2033        if a.end.cmp(&b.start, buffer).is_gt() {
2034            if a.end.cmp(&b.end, buffer).is_lt() {
2035                a.end = b.end;
2036            }
2037            ranges.remove(ix + 1);
2038        } else {
2039            ix += 1;
2040        }
2041    }
2042}
2043
2044#[cfg(any(test, feature = "unit-eval"))]
2045#[cfg_attr(not(test), allow(dead_code))]
2046pub mod test {
2047
2048    use std::sync::Arc;
2049
2050    use agent::ThreadStore;
2051    use client::{Client, UserStore};
2052    use editor::{Editor, MultiBuffer, MultiBufferOffset};
2053    use fs::FakeFs;
2054    use futures::channel::mpsc;
2055    use gpui::{AppContext, TestAppContext, UpdateGlobal as _};
2056    use language::Buffer;
2057    use project::Project;
2058    use prompt_store::PromptBuilder;
2059    use smol::stream::StreamExt as _;
2060    use util::test::marked_text_ranges;
2061    use workspace::Workspace;
2062
2063    use crate::InlineAssistant;
2064
2065    #[derive(Debug)]
2066    pub enum InlineAssistantOutput {
2067        Success {
2068            completion: Option<String>,
2069            description: Option<String>,
2070            full_buffer_text: String,
2071        },
2072        Failure {
2073            failure: String,
2074        },
2075        // These fields are used for logging
2076        #[allow(unused)]
2077        Malformed {
2078            completion: Option<String>,
2079            description: Option<String>,
2080            failure: Option<String>,
2081        },
2082    }
2083
2084    pub fn run_inline_assistant_test<SetupF, TestF>(
2085        base_buffer: String,
2086        prompt: String,
2087        setup: SetupF,
2088        test: TestF,
2089        cx: &mut TestAppContext,
2090    ) -> InlineAssistantOutput
2091    where
2092        SetupF: FnOnce(&mut gpui::VisualTestContext),
2093        TestF: FnOnce(&mut gpui::VisualTestContext),
2094    {
2095        let fs = FakeFs::new(cx.executor());
2096        let app_state = cx.update(|cx| workspace::AppState::test(cx));
2097        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2098        let http = Arc::new(reqwest_client::ReqwestClient::user_agent("agent tests").unwrap());
2099        let client = cx.update(|cx| {
2100            cx.set_http_client(http);
2101            Client::production(cx)
2102        });
2103        let mut inline_assistant = InlineAssistant::new(fs.clone(), prompt_builder);
2104
2105        let (tx, mut completion_rx) = mpsc::unbounded();
2106        inline_assistant.set_completion_receiver(tx);
2107
2108        // Initialize settings and client
2109        cx.update(|cx| {
2110            gpui_tokio::init(cx);
2111            settings::init(cx);
2112            client::init(&client, cx);
2113            workspace::init(app_state.clone(), cx);
2114            let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2115            language_model::init(client.clone(), cx);
2116            language_models::init(user_store, client.clone(), cx);
2117
2118            cx.set_global(inline_assistant);
2119        });
2120
2121        let foreground_executor = cx.foreground_executor().clone();
2122        let project =
2123            foreground_executor.block_test(async { Project::test(fs.clone(), [], cx).await });
2124
2125        // Create workspace with window
2126        let (workspace, cx) = cx.add_window_view(|window, cx| {
2127            window.activate_window();
2128            Workspace::new(None, project.clone(), app_state.clone(), window, cx)
2129        });
2130
2131        setup(cx);
2132
2133        let (_editor, buffer, _history) = cx.update(|window, cx| {
2134            let buffer = cx.new(|cx| Buffer::local("", cx));
2135            let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2136            let editor = cx.new(|cx| Editor::for_multibuffer(multibuffer, None, window, cx));
2137            editor.update(cx, |editor, cx| {
2138                let (unmarked_text, selection_ranges) = marked_text_ranges(&base_buffer, true);
2139                editor.set_text(unmarked_text, window, cx);
2140                editor.change_selections(Default::default(), window, cx, |s| {
2141                    s.select_ranges(
2142                        selection_ranges.into_iter().map(|range| {
2143                            MultiBufferOffset(range.start)..MultiBufferOffset(range.end)
2144                        }),
2145                    )
2146                })
2147            });
2148
2149            let thread_store = cx.new(|cx| ThreadStore::new(cx));
2150            let history = cx.new(|cx| crate::acp::AcpThreadHistory::new(None, window, cx));
2151
2152            // Add editor to workspace
2153            workspace.update(cx, |workspace, cx| {
2154                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2155            });
2156
2157            // Call assist method
2158            InlineAssistant::update_global(cx, |inline_assistant, cx| {
2159                let assist_id = inline_assistant
2160                    .assist(
2161                        &editor,
2162                        workspace.downgrade(),
2163                        project.downgrade(),
2164                        thread_store,
2165                        None,
2166                        history.downgrade(),
2167                        Some(prompt),
2168                        window,
2169                        cx,
2170                    )
2171                    .unwrap();
2172
2173                inline_assistant.start_assist(assist_id, window, cx);
2174            });
2175
2176            (editor, buffer, history)
2177        });
2178
2179        cx.run_until_parked();
2180
2181        test(cx);
2182
2183        let assist_id = foreground_executor
2184            .block_test(async { completion_rx.next().await })
2185            .unwrap()
2186            .unwrap();
2187
2188        let (completion, description, failure) = cx.update(|_, cx| {
2189            InlineAssistant::update_global(cx, |inline_assistant, cx| {
2190                let codegen = inline_assistant.get_codegen(assist_id, cx).unwrap();
2191
2192                let completion = codegen.read(cx).current_completion();
2193                let description = codegen.read(cx).current_description();
2194                let failure = codegen.read(cx).current_failure();
2195
2196                (completion, description, failure)
2197            })
2198        });
2199
2200        if failure.is_some() && (completion.is_some() || description.is_some()) {
2201            InlineAssistantOutput::Malformed {
2202                completion,
2203                description,
2204                failure,
2205            }
2206        } else if let Some(failure) = failure {
2207            InlineAssistantOutput::Failure { failure }
2208        } else {
2209            InlineAssistantOutput::Success {
2210                completion,
2211                description,
2212                full_buffer_text: buffer.read_with(cx, |buffer, _| buffer.text()),
2213            }
2214        }
2215    }
2216}
2217
2218#[cfg(any(test, feature = "unit-eval"))]
2219#[cfg_attr(not(test), allow(dead_code))]
2220pub mod evals {
2221    use std::str::FromStr;
2222
2223    use eval_utils::{EvalOutput, NoProcessor};
2224    use gpui::TestAppContext;
2225    use language_model::{LanguageModelRegistry, SelectedModel};
2226
2227    use crate::inline_assistant::test::{InlineAssistantOutput, run_inline_assistant_test};
2228
2229    #[test]
2230    #[cfg_attr(not(feature = "unit-eval"), ignore)]
2231    fn eval_single_cursor_edit() {
2232        run_eval(
2233            20,
2234            1.0,
2235            "Rename this variable to buffer_text".to_string(),
2236            indoc::indoc! {"
2237                struct EvalExampleStruct {
2238                    text: Strˇing,
2239                    prompt: String,
2240                }
2241            "}
2242            .to_string(),
2243            exact_buffer_match(indoc::indoc! {"
2244                struct EvalExampleStruct {
2245                    buffer_text: String,
2246                    prompt: String,
2247                }
2248            "}),
2249        );
2250    }
2251
2252    #[test]
2253    #[cfg_attr(not(feature = "unit-eval"), ignore)]
2254    fn eval_cant_do() {
2255        run_eval(
2256            20,
2257            0.95,
2258            "Rename the struct to EvalExampleStructNope",
2259            indoc::indoc! {"
2260                struct EvalExampleStruct {
2261                    text: Strˇing,
2262                    prompt: String,
2263                }
2264            "},
2265            uncertain_output,
2266        );
2267    }
2268
2269    #[test]
2270    #[cfg_attr(not(feature = "unit-eval"), ignore)]
2271    fn eval_unclear() {
2272        run_eval(
2273            20,
2274            0.95,
2275            "Make exactly the change I want you to make",
2276            indoc::indoc! {"
2277                struct EvalExampleStruct {
2278                    text: Strˇing,
2279                    prompt: String,
2280                }
2281            "},
2282            uncertain_output,
2283        );
2284    }
2285
2286    #[test]
2287    #[cfg_attr(not(feature = "unit-eval"), ignore)]
2288    fn eval_empty_buffer() {
2289        run_eval(
2290            20,
2291            1.0,
2292            "Write a Python hello, world program".to_string(),
2293            "ˇ".to_string(),
2294            |output| match output {
2295                InlineAssistantOutput::Success {
2296                    full_buffer_text, ..
2297                } => {
2298                    if full_buffer_text.is_empty() {
2299                        EvalOutput::failed("expected some output".to_string())
2300                    } else {
2301                        EvalOutput::passed(format!("Produced {full_buffer_text}"))
2302                    }
2303                }
2304                o @ InlineAssistantOutput::Failure { .. } => EvalOutput::failed(format!(
2305                    "Assistant output does not match expected output: {:?}",
2306                    o
2307                )),
2308                o @ InlineAssistantOutput::Malformed { .. } => EvalOutput::failed(format!(
2309                    "Assistant output does not match expected output: {:?}",
2310                    o
2311                )),
2312            },
2313        );
2314    }
2315
2316    fn run_eval(
2317        iterations: usize,
2318        expected_pass_ratio: f32,
2319        prompt: impl Into<String>,
2320        buffer: impl Into<String>,
2321        judge: impl Fn(InlineAssistantOutput) -> eval_utils::EvalOutput<()> + Send + Sync + 'static,
2322    ) {
2323        let buffer = buffer.into();
2324        let prompt = prompt.into();
2325
2326        eval_utils::eval(iterations, expected_pass_ratio, NoProcessor, move || {
2327            let dispatcher = gpui::TestDispatcher::new(rand::random());
2328            let mut cx = TestAppContext::build(dispatcher, None);
2329            cx.skip_drawing();
2330
2331            let output = run_inline_assistant_test(
2332                buffer.clone(),
2333                prompt.clone(),
2334                |cx| {
2335                    // Reconfigure to use a real model instead of the fake one
2336                    let model_name = std::env::var("ZED_AGENT_MODEL")
2337                        .unwrap_or("anthropic/claude-sonnet-4-latest".into());
2338
2339                    let selected_model = SelectedModel::from_str(&model_name)
2340                        .expect("Invalid model format. Use 'provider/model-id'");
2341
2342                    log::info!("Selected model: {selected_model:?}");
2343
2344                    cx.update(|_, cx| {
2345                        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2346                            registry.select_inline_assistant_model(Some(&selected_model), cx);
2347                        });
2348                    });
2349                },
2350                |_cx| {
2351                    log::info!("Waiting for actual response from the LLM...");
2352                },
2353                &mut cx,
2354            );
2355
2356            cx.quit();
2357
2358            judge(output)
2359        });
2360    }
2361
2362    fn uncertain_output(output: InlineAssistantOutput) -> EvalOutput<()> {
2363        match &output {
2364            o @ InlineAssistantOutput::Success {
2365                completion,
2366                description,
2367                ..
2368            } => {
2369                if description.is_some() && completion.is_none() {
2370                    EvalOutput::passed(format!(
2371                        "Assistant produced no completion, but a description:\n{}",
2372                        description.as_ref().unwrap()
2373                    ))
2374                } else {
2375                    EvalOutput::failed(format!("Assistant produced a completion:\n{:?}", o))
2376                }
2377            }
2378            InlineAssistantOutput::Failure {
2379                failure: error_message,
2380            } => EvalOutput::passed(format!(
2381                "Assistant produced a failure message: {}",
2382                error_message
2383            )),
2384            o @ InlineAssistantOutput::Malformed { .. } => {
2385                EvalOutput::failed(format!("Assistant produced a malformed response:\n{:?}", o))
2386            }
2387        }
2388    }
2389
2390    fn exact_buffer_match(
2391        correct_output: impl Into<String>,
2392    ) -> impl Fn(InlineAssistantOutput) -> EvalOutput<()> {
2393        let correct_output = correct_output.into();
2394        move |output| match output {
2395            InlineAssistantOutput::Success {
2396                description,
2397                full_buffer_text,
2398                ..
2399            } => {
2400                if full_buffer_text == correct_output && description.is_none() {
2401                    EvalOutput::passed("Assistant output matches")
2402                } else if full_buffer_text == correct_output {
2403                    EvalOutput::failed(format!(
2404                        "Assistant output produced an unescessary description description:\n{:?}",
2405                        description
2406                    ))
2407                } else {
2408                    EvalOutput::failed(format!(
2409                        "Assistant output does not match expected output:\n{:?}\ndescription:\n{:?}",
2410                        full_buffer_text, description
2411                    ))
2412                }
2413            }
2414            o @ InlineAssistantOutput::Failure { .. } => EvalOutput::failed(format!(
2415                "Assistant output does not match expected output: {:?}",
2416                o
2417            )),
2418            o @ InlineAssistantOutput::Malformed { .. } => EvalOutput::failed(format!(
2419                "Assistant output does not match expected output: {:?}",
2420                o
2421            )),
2422        }
2423    }
2424}