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