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