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