inline_assistant.rs

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