inline_assistant.rs

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