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)))
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));
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 mut scroll_target_top = scroll_target_range.0;
1263            let mut scroll_target_bottom = scroll_target_range.1;
1264
1265            scroll_target_top -= editor.vertical_scroll_margin() as ScrollOffset;
1266            scroll_target_bottom += editor.vertical_scroll_margin() as ScrollOffset;
1267
1268            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1269            let scroll_top = editor.scroll_position(cx).y;
1270            let scroll_bottom = scroll_top + height_in_lines;
1271
1272            if scroll_target_top < scroll_top {
1273                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1274            } else if scroll_target_bottom > scroll_bottom {
1275                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1276                    editor.set_scroll_position(
1277                        point(0., scroll_target_bottom - height_in_lines),
1278                        window,
1279                        cx,
1280                    );
1281                } else {
1282                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1283                }
1284            }
1285        });
1286    }
1287
1288    fn unlink_assist_group(
1289        &mut self,
1290        assist_group_id: InlineAssistGroupId,
1291        window: &mut Window,
1292        cx: &mut App,
1293    ) -> Vec<InlineAssistId> {
1294        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1295        assist_group.linked = false;
1296
1297        for assist_id in &assist_group.assist_ids {
1298            let assist = self.assists.get_mut(assist_id).unwrap();
1299            if let Some(editor_decorations) = assist.decorations.as_ref() {
1300                editor_decorations
1301                    .prompt_editor
1302                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1303            }
1304        }
1305        assist_group.assist_ids.clone()
1306    }
1307
1308    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1309        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1310            assist
1311        } else {
1312            return;
1313        };
1314
1315        let assist_group_id = assist.group_id;
1316        if self.assist_groups[&assist_group_id].linked {
1317            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1318                self.start_assist(assist_id, window, cx);
1319            }
1320            return;
1321        }
1322
1323        let Some((user_prompt, mention_set)) = assist.user_prompt(cx).zip(assist.mention_set(cx))
1324        else {
1325            return;
1326        };
1327
1328        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1329        self.prompt_history.push_back(user_prompt.clone());
1330        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1331            self.prompt_history.pop_front();
1332        }
1333
1334        let Some(ConfiguredModel { model, .. }) =
1335            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1336        else {
1337            return;
1338        };
1339
1340        let context_task = load_context(&mention_set, cx).shared();
1341        assist
1342            .codegen
1343            .update(cx, |codegen, cx| {
1344                codegen.start(model, user_prompt, context_task, cx)
1345            })
1346            .log_err();
1347    }
1348
1349    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1350        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1351            assist
1352        } else {
1353            return;
1354        };
1355
1356        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1357    }
1358
1359    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1360        let mut gutter_pending_ranges = Vec::new();
1361        let mut gutter_transformed_ranges = Vec::new();
1362        let mut foreground_ranges = Vec::new();
1363        let mut inserted_row_ranges = Vec::new();
1364        let empty_assist_ids = Vec::new();
1365        let assist_ids = self
1366            .assists_by_editor
1367            .get(&editor.downgrade())
1368            .map_or(&empty_assist_ids, |editor_assists| {
1369                &editor_assists.assist_ids
1370            });
1371
1372        for assist_id in assist_ids {
1373            if let Some(assist) = self.assists.get(assist_id) {
1374                let codegen = assist.codegen.read(cx);
1375                let buffer = codegen.buffer(cx).read(cx).read(cx);
1376                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1377
1378                let pending_range =
1379                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1380                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1381                    gutter_pending_ranges.push(pending_range);
1382                }
1383
1384                if let Some(edit_position) = codegen.edit_position(cx) {
1385                    let edited_range = assist.range.start..edit_position;
1386                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1387                        gutter_transformed_ranges.push(edited_range);
1388                    }
1389                }
1390
1391                if assist.decorations.is_some() {
1392                    inserted_row_ranges
1393                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1394                }
1395            }
1396        }
1397
1398        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1399        merge_ranges(&mut foreground_ranges, &snapshot);
1400        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1401        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1402        editor.update(cx, |editor, cx| {
1403            enum GutterPendingRange {}
1404            if gutter_pending_ranges.is_empty() {
1405                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1406            } else {
1407                editor.highlight_gutter::<GutterPendingRange>(
1408                    gutter_pending_ranges,
1409                    |cx| cx.theme().status().info_background,
1410                    cx,
1411                )
1412            }
1413
1414            enum GutterTransformedRange {}
1415            if gutter_transformed_ranges.is_empty() {
1416                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1417            } else {
1418                editor.highlight_gutter::<GutterTransformedRange>(
1419                    gutter_transformed_ranges,
1420                    |cx| cx.theme().status().info,
1421                    cx,
1422                )
1423            }
1424
1425            if foreground_ranges.is_empty() {
1426                editor.clear_highlights::<InlineAssist>(cx);
1427            } else {
1428                editor.highlight_text::<InlineAssist>(
1429                    foreground_ranges,
1430                    HighlightStyle {
1431                        fade_out: Some(0.6),
1432                        ..Default::default()
1433                    },
1434                    cx,
1435                );
1436            }
1437
1438            editor.clear_row_highlights::<InlineAssist>();
1439            for row_range in inserted_row_ranges {
1440                editor.highlight_rows::<InlineAssist>(
1441                    row_range,
1442                    cx.theme().status().info_background,
1443                    Default::default(),
1444                    cx,
1445                );
1446            }
1447        });
1448    }
1449
1450    fn update_editor_blocks(
1451        &mut self,
1452        editor: &Entity<Editor>,
1453        assist_id: InlineAssistId,
1454        window: &mut Window,
1455        cx: &mut App,
1456    ) {
1457        let Some(assist) = self.assists.get_mut(&assist_id) else {
1458            return;
1459        };
1460        let Some(decorations) = assist.decorations.as_mut() else {
1461            return;
1462        };
1463
1464        let codegen = assist.codegen.read(cx);
1465        let old_snapshot = codegen.snapshot(cx);
1466        let old_buffer = codegen.old_buffer(cx);
1467        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1468
1469        editor.update(cx, |editor, cx| {
1470            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1471            editor.remove_blocks(old_blocks, None, cx);
1472
1473            let mut new_blocks = Vec::new();
1474            for (new_row, old_row_range) in deleted_row_ranges {
1475                let (_, buffer_start) = old_snapshot
1476                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1477                    .unwrap();
1478                let (_, buffer_end) = old_snapshot
1479                    .point_to_buffer_offset(Point::new(
1480                        *old_row_range.end(),
1481                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1482                    ))
1483                    .unwrap();
1484
1485                let deleted_lines_editor = cx.new(|cx| {
1486                    let multi_buffer =
1487                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1488                    multi_buffer.update(cx, |multi_buffer, cx| {
1489                        multi_buffer.push_excerpts(
1490                            old_buffer.clone(),
1491                            // todo(lw): buffer_start and buffer_end might come from different snapshots!
1492                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1493                            cx,
1494                        );
1495                    });
1496
1497                    enum DeletedLines {}
1498                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1499                    editor.disable_scrollbars_and_minimap(window, cx);
1500                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1501                    editor.set_show_wrap_guides(false, cx);
1502                    editor.set_show_gutter(false, cx);
1503                    editor.set_offset_content(false, cx);
1504                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1505                    editor.set_read_only(true);
1506                    editor.set_show_edit_predictions(Some(false), window, cx);
1507                    editor.highlight_rows::<DeletedLines>(
1508                        Anchor::min()..Anchor::max(),
1509                        cx.theme().status().deleted_background,
1510                        Default::default(),
1511                        cx,
1512                    );
1513                    editor
1514                });
1515
1516                let height =
1517                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1518                new_blocks.push(BlockProperties {
1519                    placement: BlockPlacement::Above(new_row),
1520                    height: Some(height),
1521                    style: BlockStyle::Flex,
1522                    render: Arc::new(move |cx| {
1523                        div()
1524                            .block_mouse_except_scroll()
1525                            .bg(cx.theme().status().deleted_background)
1526                            .size_full()
1527                            .h(height as f32 * cx.window.line_height())
1528                            .pl(cx.margins.gutter.full_width())
1529                            .child(deleted_lines_editor.clone())
1530                            .into_any_element()
1531                    }),
1532                    priority: 0,
1533                });
1534            }
1535
1536            decorations.removed_line_block_ids = editor
1537                .insert_blocks(new_blocks, None, cx)
1538                .into_iter()
1539                .collect();
1540        })
1541    }
1542
1543    fn resolve_inline_assist_target(
1544        workspace: &mut Workspace,
1545        agent_panel: Option<Entity<AgentPanel>>,
1546        window: &mut Window,
1547        cx: &mut App,
1548    ) -> Option<InlineAssistTarget> {
1549        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx)
1550            && terminal_panel
1551                .read(cx)
1552                .focus_handle(cx)
1553                .contains_focused(window, cx)
1554            && let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1555                pane.read(cx)
1556                    .active_item()
1557                    .and_then(|t| t.downcast::<TerminalView>())
1558            })
1559        {
1560            return Some(InlineAssistTarget::Terminal(terminal_view));
1561        }
1562
1563        let text_thread_editor = agent_panel
1564            .and_then(|panel| panel.read(cx).active_text_thread_editor())
1565            .and_then(|editor| {
1566                let editor = &editor.read(cx).editor().clone();
1567                if editor.read(cx).is_focused(window) {
1568                    Some(editor.clone())
1569                } else {
1570                    None
1571                }
1572            });
1573
1574        if let Some(text_thread_editor) = text_thread_editor {
1575            Some(InlineAssistTarget::Editor(text_thread_editor))
1576        } else if let Some(workspace_editor) = workspace
1577            .active_item(cx)
1578            .and_then(|item| item.act_as::<Editor>(cx))
1579        {
1580            Some(InlineAssistTarget::Editor(workspace_editor))
1581        } else {
1582            workspace
1583                .active_item(cx)
1584                .and_then(|item| item.act_as::<TerminalView>(cx))
1585                .map(InlineAssistTarget::Terminal)
1586        }
1587    }
1588
1589    #[cfg(any(test, feature = "test-support"))]
1590    pub fn set_completion_receiver(
1591        &mut self,
1592        sender: mpsc::UnboundedSender<anyhow::Result<InlineAssistId>>,
1593    ) {
1594        self._inline_assistant_completions = Some(sender);
1595    }
1596
1597    #[cfg(any(test, feature = "test-support"))]
1598    pub fn get_codegen(
1599        &mut self,
1600        assist_id: InlineAssistId,
1601        cx: &mut App,
1602    ) -> Option<Entity<CodegenAlternative>> {
1603        self.assists.get(&assist_id).map(|inline_assist| {
1604            inline_assist
1605                .codegen
1606                .update(cx, |codegen, _cx| codegen.active_alternative().clone())
1607        })
1608    }
1609}
1610
1611struct EditorInlineAssists {
1612    assist_ids: Vec<InlineAssistId>,
1613    scroll_lock: Option<InlineAssistScrollLock>,
1614    highlight_updates: watch::Sender<()>,
1615    _update_highlights: Task<Result<()>>,
1616    _subscriptions: Vec<gpui::Subscription>,
1617}
1618
1619struct InlineAssistScrollLock {
1620    assist_id: InlineAssistId,
1621    distance_from_top: ScrollOffset,
1622}
1623
1624impl EditorInlineAssists {
1625    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1626        let (highlight_updates_tx, mut highlight_updates_rx) = watch::channel(());
1627        Self {
1628            assist_ids: Vec::new(),
1629            scroll_lock: None,
1630            highlight_updates: highlight_updates_tx,
1631            _update_highlights: cx.spawn({
1632                let editor = editor.downgrade();
1633                async move |cx| {
1634                    while let Ok(()) = highlight_updates_rx.changed().await {
1635                        let editor = editor.upgrade().context("editor was dropped")?;
1636                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1637                            assistant.update_editor_highlights(&editor, cx);
1638                        })?;
1639                    }
1640                    Ok(())
1641                }
1642            }),
1643            _subscriptions: vec![
1644                cx.observe_release_in(editor, window, {
1645                    let editor = editor.downgrade();
1646                    |_, window, cx| {
1647                        InlineAssistant::update_global(cx, |this, cx| {
1648                            this.handle_editor_release(editor, window, cx);
1649                        })
1650                    }
1651                }),
1652                window.observe(editor, cx, move |editor, window, cx| {
1653                    InlineAssistant::update_global(cx, |this, cx| {
1654                        this.handle_editor_change(editor, window, cx)
1655                    })
1656                }),
1657                window.subscribe(editor, cx, move |editor, event, window, cx| {
1658                    InlineAssistant::update_global(cx, |this, cx| {
1659                        this.handle_editor_event(editor, event, window, cx)
1660                    })
1661                }),
1662                editor.update(cx, |editor, cx| {
1663                    let editor_handle = cx.entity().downgrade();
1664                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1665                        InlineAssistant::update_global(cx, |this, cx| {
1666                            if let Some(editor) = editor_handle.upgrade() {
1667                                this.handle_editor_newline(editor, window, cx)
1668                            }
1669                        })
1670                    })
1671                }),
1672                editor.update(cx, |editor, cx| {
1673                    let editor_handle = cx.entity().downgrade();
1674                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1675                        InlineAssistant::update_global(cx, |this, cx| {
1676                            if let Some(editor) = editor_handle.upgrade() {
1677                                this.handle_editor_cancel(editor, window, cx)
1678                            }
1679                        })
1680                    })
1681                }),
1682            ],
1683        }
1684    }
1685}
1686
1687struct InlineAssistGroup {
1688    assist_ids: Vec<InlineAssistId>,
1689    linked: bool,
1690    active_assist_id: Option<InlineAssistId>,
1691}
1692
1693impl InlineAssistGroup {
1694    fn new() -> Self {
1695        Self {
1696            assist_ids: Vec::new(),
1697            linked: true,
1698            active_assist_id: None,
1699        }
1700    }
1701}
1702
1703fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1704    let editor = editor.clone();
1705
1706    Arc::new(move |cx: &mut BlockContext| {
1707        let editor_margins = editor.read(cx).editor_margins();
1708
1709        *editor_margins.lock() = *cx.margins;
1710        editor.clone().into_any_element()
1711    })
1712}
1713
1714#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1715struct InlineAssistGroupId(usize);
1716
1717impl InlineAssistGroupId {
1718    fn post_inc(&mut self) -> InlineAssistGroupId {
1719        let id = *self;
1720        self.0 += 1;
1721        id
1722    }
1723}
1724
1725pub struct InlineAssist {
1726    group_id: InlineAssistGroupId,
1727    range: Range<Anchor>,
1728    editor: WeakEntity<Editor>,
1729    decorations: Option<InlineAssistDecorations>,
1730    codegen: Entity<BufferCodegen>,
1731    _subscriptions: Vec<Subscription>,
1732    workspace: WeakEntity<Workspace>,
1733}
1734
1735impl InlineAssist {
1736    fn new(
1737        assist_id: InlineAssistId,
1738        group_id: InlineAssistGroupId,
1739        editor: &Entity<Editor>,
1740        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1741        prompt_block_id: CustomBlockId,
1742        tool_description_block_id: CustomBlockId,
1743        end_block_id: CustomBlockId,
1744        range: Range<Anchor>,
1745        codegen: Entity<BufferCodegen>,
1746        workspace: WeakEntity<Workspace>,
1747        window: &mut Window,
1748        cx: &mut App,
1749    ) -> Self {
1750        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1751        InlineAssist {
1752            group_id,
1753            editor: editor.downgrade(),
1754            decorations: Some(InlineAssistDecorations {
1755                prompt_block_id,
1756                prompt_editor: prompt_editor.clone(),
1757                removed_line_block_ids: Default::default(),
1758                model_explanation: Some(tool_description_block_id),
1759                end_block_id,
1760            }),
1761            range,
1762            codegen: codegen.clone(),
1763            workspace,
1764            _subscriptions: vec![
1765                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1766                    InlineAssistant::update_global(cx, |this, cx| {
1767                        this.handle_prompt_editor_focus_in(assist_id, cx)
1768                    })
1769                }),
1770                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1771                    InlineAssistant::update_global(cx, |this, cx| {
1772                        this.handle_prompt_editor_focus_out(assist_id, cx)
1773                    })
1774                }),
1775                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1776                    InlineAssistant::update_global(cx, |this, cx| {
1777                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1778                    })
1779                }),
1780                window.observe(&codegen, cx, {
1781                    let editor = editor.downgrade();
1782                    move |_, window, cx| {
1783                        if let Some(editor) = editor.upgrade() {
1784                            InlineAssistant::update_global(cx, |this, cx| {
1785                                if let Some(editor_assists) =
1786                                    this.assists_by_editor.get_mut(&editor.downgrade())
1787                                {
1788                                    editor_assists.highlight_updates.send(()).ok();
1789                                }
1790
1791                                this.update_editor_blocks(&editor, assist_id, window, cx);
1792                            })
1793                        }
1794                    }
1795                }),
1796                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1797                    InlineAssistant::update_global(cx, |this, cx| match event {
1798                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1799                        CodegenEvent::Finished => {
1800                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1801                                assist
1802                            } else {
1803                                return;
1804                            };
1805
1806                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx)
1807                                && assist.decorations.is_none()
1808                                && let Some(workspace) = assist.workspace.upgrade()
1809                            {
1810                                #[cfg(any(test, feature = "test-support"))]
1811                                if let Some(sender) = &mut this._inline_assistant_completions {
1812                                    sender
1813                                        .unbounded_send(Err(anyhow::anyhow!(
1814                                            "Inline assistant error: {}",
1815                                            error
1816                                        )))
1817                                        .ok();
1818                                }
1819
1820                                let error = format!("Inline assistant error: {}", error);
1821                                workspace.update(cx, |workspace, cx| {
1822                                    struct InlineAssistantError;
1823
1824                                    let id = NotificationId::composite::<InlineAssistantError>(
1825                                        assist_id.0,
1826                                    );
1827
1828                                    workspace.show_toast(Toast::new(id, error), cx);
1829                                })
1830                            } else {
1831                                #[cfg(any(test, feature = "test-support"))]
1832                                if let Some(sender) = &mut this._inline_assistant_completions {
1833                                    sender.unbounded_send(Ok(assist_id)).ok();
1834                                }
1835                            }
1836
1837                            if assist.decorations.is_none() {
1838                                this.finish_assist(assist_id, false, window, cx);
1839                            }
1840                        }
1841                    })
1842                }),
1843            ],
1844        }
1845    }
1846
1847    fn user_prompt(&self, cx: &App) -> Option<String> {
1848        let decorations = self.decorations.as_ref()?;
1849        Some(decorations.prompt_editor.read(cx).prompt(cx))
1850    }
1851
1852    fn mention_set(&self, cx: &App) -> Option<Entity<MentionSet>> {
1853        let decorations = self.decorations.as_ref()?;
1854        Some(decorations.prompt_editor.read(cx).mention_set().clone())
1855    }
1856}
1857
1858struct InlineAssistDecorations {
1859    prompt_block_id: CustomBlockId,
1860    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1861    removed_line_block_ids: HashSet<CustomBlockId>,
1862    model_explanation: Option<CustomBlockId>,
1863    end_block_id: CustomBlockId,
1864}
1865
1866struct AssistantCodeActionProvider {
1867    editor: WeakEntity<Editor>,
1868    workspace: WeakEntity<Workspace>,
1869}
1870
1871const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant";
1872
1873impl CodeActionProvider for AssistantCodeActionProvider {
1874    fn id(&self) -> Arc<str> {
1875        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1876    }
1877
1878    fn code_actions(
1879        &self,
1880        buffer: &Entity<Buffer>,
1881        range: Range<text::Anchor>,
1882        _: &mut Window,
1883        cx: &mut App,
1884    ) -> Task<Result<Vec<CodeAction>>> {
1885        if !AgentSettings::get_global(cx).enabled(cx) {
1886            return Task::ready(Ok(Vec::new()));
1887        }
1888
1889        let snapshot = buffer.read(cx).snapshot();
1890        let mut range = range.to_point(&snapshot);
1891
1892        // Expand the range to line boundaries.
1893        range.start.column = 0;
1894        range.end.column = snapshot.line_len(range.end.row);
1895
1896        let mut has_diagnostics = false;
1897        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1898            range.start = cmp::min(range.start, diagnostic.range.start);
1899            range.end = cmp::max(range.end, diagnostic.range.end);
1900            has_diagnostics = true;
1901        }
1902        if has_diagnostics {
1903            let symbols_containing_start = snapshot.symbols_containing(range.start, None);
1904            if let Some(symbol) = symbols_containing_start.last() {
1905                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1906                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1907            }
1908            let symbols_containing_end = snapshot.symbols_containing(range.end, None);
1909            if let Some(symbol) = symbols_containing_end.last() {
1910                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1911                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1912            }
1913
1914            Task::ready(Ok(vec![CodeAction {
1915                server_id: language::LanguageServerId(0),
1916                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1917                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1918                    title: "Fix with Assistant".into(),
1919                    ..Default::default()
1920                })),
1921                resolved: true,
1922            }]))
1923        } else {
1924            Task::ready(Ok(Vec::new()))
1925        }
1926    }
1927
1928    fn apply_code_action(
1929        &self,
1930        buffer: Entity<Buffer>,
1931        action: CodeAction,
1932        excerpt_id: ExcerptId,
1933        _push_to_history: bool,
1934        window: &mut Window,
1935        cx: &mut App,
1936    ) -> Task<Result<ProjectTransaction>> {
1937        let editor = self.editor.clone();
1938        let workspace = self.workspace.clone();
1939        let prompt_store = PromptStore::global(cx);
1940        window.spawn(cx, async move |cx| {
1941            let workspace = workspace.upgrade().context("workspace was released")?;
1942            let thread_store = cx.update(|_window, cx| {
1943                anyhow::Ok(
1944                    workspace
1945                        .read(cx)
1946                        .panel::<AgentPanel>(cx)
1947                        .context("missing agent panel")?
1948                        .read(cx)
1949                        .thread_store()
1950                        .clone(),
1951                )
1952            })??;
1953            let editor = editor.upgrade().context("editor was released")?;
1954            let range = editor
1955                .update(cx, |editor, cx| {
1956                    editor.buffer().update(cx, |multibuffer, cx| {
1957                        let buffer = buffer.read(cx);
1958                        let multibuffer_snapshot = multibuffer.read(cx);
1959
1960                        let old_context_range =
1961                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1962                        let mut new_context_range = old_context_range.clone();
1963                        if action
1964                            .range
1965                            .start
1966                            .cmp(&old_context_range.start, buffer)
1967                            .is_lt()
1968                        {
1969                            new_context_range.start = action.range.start;
1970                        }
1971                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1972                            new_context_range.end = action.range.end;
1973                        }
1974                        drop(multibuffer_snapshot);
1975
1976                        if new_context_range != old_context_range {
1977                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1978                        }
1979
1980                        let multibuffer_snapshot = multibuffer.read(cx);
1981                        multibuffer_snapshot.anchor_range_in_excerpt(excerpt_id, action.range)
1982                    })
1983                })?
1984                .context("invalid range")?;
1985
1986            let prompt_store = prompt_store.await.ok();
1987            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1988                let assist_id = assistant.suggest_assist(
1989                    &editor,
1990                    range,
1991                    "Fix Diagnostics".into(),
1992                    None,
1993                    true,
1994                    workspace,
1995                    thread_store,
1996                    prompt_store,
1997                    window,
1998                    cx,
1999                );
2000                assistant.start_assist(assist_id, window, cx);
2001            })?;
2002
2003            Ok(ProjectTransaction::default())
2004        })
2005    }
2006}
2007
2008fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
2009    ranges.sort_unstable_by(|a, b| {
2010        a.start
2011            .cmp(&b.start, buffer)
2012            .then_with(|| b.end.cmp(&a.end, buffer))
2013    });
2014
2015    let mut ix = 0;
2016    while ix + 1 < ranges.len() {
2017        let b = ranges[ix + 1].clone();
2018        let a = &mut ranges[ix];
2019        if a.end.cmp(&b.start, buffer).is_gt() {
2020            if a.end.cmp(&b.end, buffer).is_lt() {
2021                a.end = b.end;
2022            }
2023            ranges.remove(ix + 1);
2024        } else {
2025            ix += 1;
2026        }
2027    }
2028}
2029
2030#[cfg(any(test, feature = "unit-eval"))]
2031#[cfg_attr(not(test), allow(dead_code))]
2032pub mod test {
2033
2034    use std::sync::Arc;
2035
2036    use agent::HistoryStore;
2037    use assistant_text_thread::TextThreadStore;
2038    use client::{Client, UserStore};
2039    use editor::{Editor, MultiBuffer, MultiBufferOffset};
2040    use fs::FakeFs;
2041    use futures::channel::mpsc;
2042    use gpui::{AppContext, TestAppContext, UpdateGlobal as _};
2043    use language::Buffer;
2044    use project::Project;
2045    use prompt_store::PromptBuilder;
2046    use smol::stream::StreamExt as _;
2047    use util::test::marked_text_ranges;
2048    use workspace::Workspace;
2049
2050    use crate::InlineAssistant;
2051
2052    #[derive(Debug)]
2053    pub enum InlineAssistantOutput {
2054        Success {
2055            completion: Option<String>,
2056            description: Option<String>,
2057            full_buffer_text: String,
2058        },
2059        Failure {
2060            failure: String,
2061        },
2062        // These fields are used for logging
2063        #[allow(unused)]
2064        Malformed {
2065            completion: Option<String>,
2066            description: Option<String>,
2067            failure: Option<String>,
2068        },
2069    }
2070
2071    pub fn run_inline_assistant_test<SetupF, TestF>(
2072        base_buffer: String,
2073        prompt: String,
2074        setup: SetupF,
2075        test: TestF,
2076        cx: &mut TestAppContext,
2077    ) -> InlineAssistantOutput
2078    where
2079        SetupF: FnOnce(&mut gpui::VisualTestContext),
2080        TestF: FnOnce(&mut gpui::VisualTestContext),
2081    {
2082        let fs = FakeFs::new(cx.executor());
2083        let app_state = cx.update(|cx| workspace::AppState::test(cx));
2084        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2085        let http = Arc::new(reqwest_client::ReqwestClient::user_agent("agent tests").unwrap());
2086        let client = cx.update(|cx| {
2087            cx.set_http_client(http);
2088            Client::production(cx)
2089        });
2090        let mut inline_assistant = InlineAssistant::new(fs.clone(), prompt_builder);
2091
2092        let (tx, mut completion_rx) = mpsc::unbounded();
2093        inline_assistant.set_completion_receiver(tx);
2094
2095        // Initialize settings and client
2096        cx.update(|cx| {
2097            gpui_tokio::init(cx);
2098            settings::init(cx);
2099            client::init(&client, cx);
2100            workspace::init(app_state.clone(), cx);
2101            let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2102            language_model::init(client.clone(), cx);
2103            language_models::init(user_store, client.clone(), cx);
2104
2105            cx.set_global(inline_assistant);
2106        });
2107
2108        let project = cx
2109            .executor()
2110            .block_test(async { Project::test(fs.clone(), [], cx).await });
2111
2112        // Create workspace with window
2113        let (workspace, cx) = cx.add_window_view(|window, cx| {
2114            window.activate_window();
2115            Workspace::new(None, project.clone(), app_state.clone(), window, cx)
2116        });
2117
2118        setup(cx);
2119
2120        let (_editor, buffer) = cx.update(|window, cx| {
2121            let buffer = cx.new(|cx| Buffer::local("", cx));
2122            let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2123            let editor = cx.new(|cx| Editor::for_multibuffer(multibuffer, None, window, cx));
2124            editor.update(cx, |editor, cx| {
2125                let (unmarked_text, selection_ranges) = marked_text_ranges(&base_buffer, true);
2126                editor.set_text(unmarked_text, window, cx);
2127                editor.change_selections(Default::default(), window, cx, |s| {
2128                    s.select_ranges(
2129                        selection_ranges.into_iter().map(|range| {
2130                            MultiBufferOffset(range.start)..MultiBufferOffset(range.end)
2131                        }),
2132                    )
2133                })
2134            });
2135
2136            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
2137            let history_store = cx.new(|cx| HistoryStore::new(text_thread_store, cx));
2138
2139            // Add editor to workspace
2140            workspace.update(cx, |workspace, cx| {
2141                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2142            });
2143
2144            // Call assist method
2145            InlineAssistant::update_global(cx, |inline_assistant, cx| {
2146                let assist_id = inline_assistant
2147                    .assist(
2148                        &editor,
2149                        workspace.downgrade(),
2150                        project.downgrade(),
2151                        history_store, // thread_store
2152                        None,          // prompt_store
2153                        Some(prompt),
2154                        window,
2155                        cx,
2156                    )
2157                    .unwrap();
2158
2159                inline_assistant.start_assist(assist_id, window, cx);
2160            });
2161
2162            (editor, buffer)
2163        });
2164
2165        cx.run_until_parked();
2166
2167        test(cx);
2168
2169        let assist_id = cx
2170            .executor()
2171            .block_test(async { completion_rx.next().await })
2172            .unwrap()
2173            .unwrap();
2174
2175        let (completion, description, failure) = cx.update(|_, cx| {
2176            InlineAssistant::update_global(cx, |inline_assistant, cx| {
2177                let codegen = inline_assistant.get_codegen(assist_id, cx).unwrap();
2178
2179                let completion = codegen.read(cx).current_completion();
2180                let description = codegen.read(cx).current_description();
2181                let failure = codegen.read(cx).current_failure();
2182
2183                (completion, description, failure)
2184            })
2185        });
2186
2187        if failure.is_some() && (completion.is_some() || description.is_some()) {
2188            InlineAssistantOutput::Malformed {
2189                completion,
2190                description,
2191                failure,
2192            }
2193        } else if let Some(failure) = failure {
2194            InlineAssistantOutput::Failure { failure }
2195        } else {
2196            InlineAssistantOutput::Success {
2197                completion,
2198                description,
2199                full_buffer_text: buffer.read_with(cx, |buffer, _| buffer.text()),
2200            }
2201        }
2202    }
2203}
2204
2205#[cfg(any(test, feature = "unit-eval"))]
2206#[cfg_attr(not(test), allow(dead_code))]
2207pub mod evals {
2208    use std::str::FromStr;
2209
2210    use eval_utils::{EvalOutput, NoProcessor};
2211    use gpui::TestAppContext;
2212    use language_model::{LanguageModelRegistry, SelectedModel};
2213    use rand::{SeedableRng as _, rngs::StdRng};
2214
2215    use crate::inline_assistant::test::{InlineAssistantOutput, run_inline_assistant_test};
2216
2217    #[test]
2218    #[cfg_attr(not(feature = "unit-eval"), ignore)]
2219    fn eval_single_cursor_edit() {
2220        run_eval(
2221            20,
2222            1.0,
2223            "Rename this variable to buffer_text".to_string(),
2224            indoc::indoc! {"
2225                struct EvalExampleStruct {
2226                    text: Strˇing,
2227                    prompt: String,
2228                }
2229            "}
2230            .to_string(),
2231            exact_buffer_match(indoc::indoc! {"
2232                struct EvalExampleStruct {
2233                    buffer_text: String,
2234                    prompt: String,
2235                }
2236            "}),
2237        );
2238    }
2239
2240    #[test]
2241    #[cfg_attr(not(feature = "unit-eval"), ignore)]
2242    fn eval_cant_do() {
2243        run_eval(
2244            20,
2245            0.95,
2246            "Rename the struct to EvalExampleStructNope",
2247            indoc::indoc! {"
2248                struct EvalExampleStruct {
2249                    text: Strˇing,
2250                    prompt: String,
2251                }
2252            "},
2253            uncertain_output,
2254        );
2255    }
2256
2257    #[test]
2258    #[cfg_attr(not(feature = "unit-eval"), ignore)]
2259    fn eval_unclear() {
2260        run_eval(
2261            20,
2262            0.95,
2263            "Make exactly the change I want you to make",
2264            indoc::indoc! {"
2265                struct EvalExampleStruct {
2266                    text: Strˇing,
2267                    prompt: String,
2268                }
2269            "},
2270            uncertain_output,
2271        );
2272    }
2273
2274    fn run_eval(
2275        iterations: usize,
2276        expected_pass_ratio: f32,
2277        prompt: impl Into<String>,
2278        buffer: impl Into<String>,
2279        judge: impl Fn(InlineAssistantOutput) -> eval_utils::EvalOutput<()> + Send + Sync + 'static,
2280    ) {
2281        let buffer = buffer.into();
2282        let prompt = prompt.into();
2283
2284        eval_utils::eval(iterations, expected_pass_ratio, NoProcessor, move || {
2285            let dispatcher = gpui::TestDispatcher::new(StdRng::from_os_rng());
2286            let mut cx = TestAppContext::build(dispatcher, None);
2287            cx.skip_drawing();
2288
2289            let output = run_inline_assistant_test(
2290                buffer.clone(),
2291                prompt.clone(),
2292                |cx| {
2293                    // Reconfigure to use a real model instead of the fake one
2294                    let model_name = std::env::var("ZED_AGENT_MODEL")
2295                        .unwrap_or("anthropic/claude-sonnet-4-latest".into());
2296
2297                    let selected_model = SelectedModel::from_str(&model_name)
2298                        .expect("Invalid model format. Use 'provider/model-id'");
2299
2300                    log::info!("Selected model: {selected_model:?}");
2301
2302                    cx.update(|_, cx| {
2303                        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2304                            registry.select_inline_assistant_model(Some(&selected_model), cx);
2305                        });
2306                    });
2307                },
2308                |_cx| {
2309                    log::info!("Waiting for actual response from the LLM...");
2310                },
2311                &mut cx,
2312            );
2313
2314            cx.quit();
2315
2316            judge(output)
2317        });
2318    }
2319
2320    fn uncertain_output(output: InlineAssistantOutput) -> EvalOutput<()> {
2321        match &output {
2322            o @ InlineAssistantOutput::Success {
2323                completion,
2324                description,
2325                ..
2326            } => {
2327                if description.is_some() && completion.is_none() {
2328                    EvalOutput::passed(format!(
2329                        "Assistant produced no completion, but a description:\n{}",
2330                        description.as_ref().unwrap()
2331                    ))
2332                } else {
2333                    EvalOutput::failed(format!("Assistant produced a completion:\n{:?}", o))
2334                }
2335            }
2336            InlineAssistantOutput::Failure {
2337                failure: error_message,
2338            } => EvalOutput::passed(format!(
2339                "Assistant produced a failure message: {}",
2340                error_message
2341            )),
2342            o @ InlineAssistantOutput::Malformed { .. } => {
2343                EvalOutput::failed(format!("Assistant produced a malformed response:\n{:?}", o))
2344            }
2345        }
2346    }
2347
2348    fn exact_buffer_match(
2349        correct_output: impl Into<String>,
2350    ) -> impl Fn(InlineAssistantOutput) -> EvalOutput<()> {
2351        let correct_output = correct_output.into();
2352        move |output| match output {
2353            InlineAssistantOutput::Success {
2354                description,
2355                full_buffer_text,
2356                ..
2357            } => {
2358                if full_buffer_text == correct_output && description.is_none() {
2359                    EvalOutput::passed("Assistant output matches")
2360                } else if full_buffer_text == correct_output {
2361                    EvalOutput::failed(format!(
2362                        "Assistant output produced an unescessary description description:\n{:?}",
2363                        description
2364                    ))
2365                } else {
2366                    EvalOutput::failed(format!(
2367                        "Assistant output does not match expected output:\n{:?}\ndescription:\n{:?}",
2368                        full_buffer_text, description
2369                    ))
2370                }
2371            }
2372            o @ InlineAssistantOutput::Failure { .. } => EvalOutput::failed(format!(
2373                "Assistant output does not match expected output: {:?}",
2374                o
2375            )),
2376            o @ InlineAssistantOutput::Malformed { .. } => EvalOutput::failed(format!(
2377                "Assistant output does not match expected output: {:?}",
2378                o
2379            )),
2380        }
2381    }
2382}