inline_assistant.rs

   1use std::cmp;
   2use std::mem;
   3use std::ops::Range;
   4use std::rc::Rc;
   5use std::sync::Arc;
   6
   7use crate::{
   8    AgentPanel,
   9    buffer_codegen::{BufferCodegen, CodegenAlternative, CodegenEvent},
  10    inline_prompt_editor::{CodegenStatus, InlineAssistId, PromptEditor, PromptEditorEvent},
  11    terminal_inline_assistant::TerminalInlineAssistant,
  12};
  13use agent::{
  14    context_store::ContextStore,
  15    thread_store::{TextThreadStore, ThreadStore},
  16};
  17use agent_settings::AgentSettings;
  18use anyhow::{Context as _, Result};
  19use client::telemetry::Telemetry;
  20use collections::{HashMap, HashSet, VecDeque, hash_map};
  21use editor::SelectionEffects;
  22use editor::{
  23    Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorEvent, ExcerptId, ExcerptRange,
  24    MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint,
  25    actions::SelectAll,
  26    display_map::{
  27        BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, EditorMargins,
  28        RenderBlock, ToDisplayPoint,
  29    },
  30};
  31use fs::Fs;
  32use gpui::{
  33    App, Context, Entity, Focusable, Global, HighlightStyle, Subscription, Task, UpdateGlobal,
  34    WeakEntity, Window, point,
  35};
  36use language::{Buffer, Point, Selection, TransactionId};
  37use language_model::{
  38    ConfigurationError, ConfiguredModel, LanguageModelRegistry, report_assistant_event,
  39};
  40use multi_buffer::MultiBufferRow;
  41use parking_lot::Mutex;
  42use project::{CodeAction, DisableAiSettings, LspAction, Project, ProjectTransaction};
  43use prompt_store::{PromptBuilder, PromptStore};
  44use settings::{Settings, SettingsStore};
  45use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
  46use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
  47use text::{OffsetRangeExt, ToPoint as _};
  48use ui::prelude::*;
  49use util::{RangeExt, ResultExt, maybe};
  50use workspace::{ItemHandle, Toast, Workspace, dock::Panel, notifications::NotificationId};
  51use zed_actions::agent::OpenSettings;
  52
  53pub fn init(
  54    fs: Arc<dyn Fs>,
  55    prompt_builder: Arc<PromptBuilder>,
  56    telemetry: Arc<Telemetry>,
  57    cx: &mut App,
  58) {
  59    cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));
  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    telemetry: Arc<Telemetry>,
 100    fs: Arc<dyn Fs>,
 101}
 102
 103impl Global for InlineAssistant {}
 104
 105impl InlineAssistant {
 106    pub fn new(
 107        fs: Arc<dyn Fs>,
 108        prompt_builder: Arc<PromptBuilder>,
 109        telemetry: Arc<Telemetry>,
 110    ) -> Self {
 111        Self {
 112            next_assist_id: InlineAssistId::default(),
 113            next_assist_group_id: InlineAssistGroupId::default(),
 114            assists: HashMap::default(),
 115            assists_by_editor: HashMap::default(),
 116            assist_groups: HashMap::default(),
 117            confirmed_assists: HashMap::default(),
 118            prompt_history: VecDeque::default(),
 119            prompt_builder,
 120            telemetry,
 121            fs,
 122        }
 123    }
 124
 125    pub fn register_workspace(
 126        &mut self,
 127        workspace: &Entity<Workspace>,
 128        window: &mut Window,
 129        cx: &mut App,
 130    ) {
 131        window
 132            .subscribe(workspace, cx, |workspace, event, window, cx| {
 133                Self::update_global(cx, |this, cx| {
 134                    this.handle_workspace_event(workspace, event, window, cx)
 135                });
 136            })
 137            .detach();
 138
 139        let workspace = workspace.downgrade();
 140        cx.observe_global::<SettingsStore>(move |cx| {
 141            let Some(workspace) = workspace.upgrade() else {
 142                return;
 143            };
 144            let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
 145                return;
 146            };
 147            let enabled = AgentSettings::get_global(cx).enabled;
 148            terminal_panel.update(cx, |terminal_panel, cx| {
 149                terminal_panel.set_assistant_enabled(enabled, cx)
 150            });
 151        })
 152        .detach();
 153    }
 154
 155    /// Hides all active inline assists when AI is disabled
 156    pub fn cancel_all_active_completions(&mut self, cx: &mut App) {
 157        // Cancel all active completions in editors
 158        for (editor_handle, _) in self.assists_by_editor.iter() {
 159            if let Some(editor) = editor_handle.upgrade() {
 160                let windows = cx.windows();
 161                if !windows.is_empty() {
 162                    let window = windows[0];
 163                    let _ = window.update(cx, |_, window, cx| {
 164                        editor.update(cx, |editor, cx| {
 165                            if editor.has_active_edit_prediction() {
 166                                editor.cancel(&Default::default(), window, cx);
 167                            }
 168                        });
 169                    });
 170                }
 171            }
 172        }
 173    }
 174
 175    fn handle_workspace_event(
 176        &mut self,
 177        workspace: Entity<Workspace>,
 178        event: &workspace::Event,
 179        window: &mut Window,
 180        cx: &mut App,
 181    ) {
 182        match event {
 183            workspace::Event::UserSavedItem { item, .. } => {
 184                // When the user manually saves an editor, automatically accepts all finished transformations.
 185                if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx))
 186                    && let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade())
 187                {
 188                    for assist_id in editor_assists.assist_ids.clone() {
 189                        let assist = &self.assists[&assist_id];
 190                        if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
 191                            self.finish_assist(assist_id, false, window, cx)
 192                        }
 193                    }
 194                }
 195            }
 196            workspace::Event::ItemAdded { item } => {
 197                self.register_workspace_item(&workspace, item.as_ref(), window, cx);
 198            }
 199            _ => (),
 200        }
 201    }
 202
 203    fn register_workspace_item(
 204        &mut self,
 205        workspace: &Entity<Workspace>,
 206        item: &dyn ItemHandle,
 207        window: &mut Window,
 208        cx: &mut App,
 209    ) {
 210        let is_assistant2_enabled = !DisableAiSettings::get_global(cx).disable_ai;
 211
 212        if let Some(editor) = item.act_as::<Editor>(cx) {
 213            editor.update(cx, |editor, cx| {
 214                if is_assistant2_enabled {
 215                    let panel = workspace.read(cx).panel::<AgentPanel>(cx);
 216                    let thread_store = panel
 217                        .as_ref()
 218                        .map(|agent_panel| agent_panel.read(cx).thread_store().downgrade());
 219                    let text_thread_store = panel
 220                        .map(|agent_panel| agent_panel.read(cx).text_thread_store().downgrade());
 221
 222                    editor.add_code_action_provider(
 223                        Rc::new(AssistantCodeActionProvider {
 224                            editor: cx.entity().downgrade(),
 225                            workspace: workspace.downgrade(),
 226                            thread_store,
 227                            text_thread_store,
 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
 240                    // Remove the Assistant1 code action provider, as it still might be registered.
 241                    editor.remove_code_action_provider("assistant".into(), window, cx);
 242                } else {
 243                    editor.remove_code_action_provider(
 244                        ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
 245                        window,
 246                        cx,
 247                    );
 248                }
 249            });
 250        }
 251    }
 252
 253    pub fn inline_assist(
 254        workspace: &mut Workspace,
 255        action: &zed_actions::assistant::InlineAssist,
 256        window: &mut Window,
 257        cx: &mut Context<Workspace>,
 258    ) {
 259        let settings = AgentSettings::get_global(cx);
 260        if !settings.enabled || DisableAiSettings::get_global(cx).disable_ai {
 261            return;
 262        }
 263
 264        let Some(inline_assist_target) = Self::resolve_inline_assist_target(
 265            workspace,
 266            workspace.panel::<AgentPanel>(cx),
 267            window,
 268            cx,
 269        ) else {
 270            return;
 271        };
 272
 273        let configuration_error = || {
 274            let model_registry = LanguageModelRegistry::read_global(cx);
 275            model_registry.configuration_error(model_registry.inline_assistant_model(), cx)
 276        };
 277
 278        let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) else {
 279            return;
 280        };
 281        let agent_panel = agent_panel.read(cx);
 282
 283        let prompt_store = agent_panel.prompt_store().as_ref().cloned();
 284        let thread_store = Some(agent_panel.thread_store().downgrade());
 285        let text_thread_store = Some(agent_panel.text_thread_store().downgrade());
 286        let context_store = agent_panel.inline_assist_context_store().clone();
 287
 288        let handle_assist =
 289            |window: &mut Window, cx: &mut Context<Workspace>| match inline_assist_target {
 290                InlineAssistTarget::Editor(active_editor) => {
 291                    InlineAssistant::update_global(cx, |assistant, cx| {
 292                        assistant.assist(
 293                            &active_editor,
 294                            cx.entity().downgrade(),
 295                            context_store,
 296                            workspace.project().downgrade(),
 297                            prompt_store,
 298                            thread_store,
 299                            text_thread_store,
 300                            action.prompt.clone(),
 301                            window,
 302                            cx,
 303                        )
 304                    })
 305                }
 306                InlineAssistTarget::Terminal(active_terminal) => {
 307                    TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 308                        assistant.assist(
 309                            &active_terminal,
 310                            cx.entity().downgrade(),
 311                            workspace.project().downgrade(),
 312                            prompt_store,
 313                            thread_store,
 314                            text_thread_store,
 315                            action.prompt.clone(),
 316                            window,
 317                            cx,
 318                        )
 319                    })
 320                }
 321            };
 322
 323        if let Some(error) = configuration_error() {
 324            if let ConfigurationError::ProviderNotAuthenticated(provider) = error {
 325                cx.spawn(async move |_, cx| {
 326                    cx.update(|cx| provider.authenticate(cx))?.await?;
 327                    anyhow::Ok(())
 328                })
 329                .detach_and_log_err(cx);
 330
 331                if configuration_error().is_none() {
 332                    handle_assist(window, cx);
 333                }
 334            } else {
 335                cx.spawn_in(window, async move |_, cx| {
 336                    let answer = cx
 337                        .prompt(
 338                            gpui::PromptLevel::Warning,
 339                            &error.to_string(),
 340                            None,
 341                            &["Configure", "Cancel"],
 342                        )
 343                        .await
 344                        .ok();
 345                    if let Some(answer) = answer
 346                        && answer == 0
 347                    {
 348                        cx.update(|window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
 349                            .ok();
 350                    }
 351                    anyhow::Ok(())
 352                })
 353                .detach_and_log_err(cx);
 354            }
 355        } else {
 356            handle_assist(window, cx);
 357        }
 358    }
 359
 360    pub fn assist(
 361        &mut self,
 362        editor: &Entity<Editor>,
 363        workspace: WeakEntity<Workspace>,
 364        context_store: Entity<ContextStore>,
 365        project: WeakEntity<Project>,
 366        prompt_store: Option<Entity<PromptStore>>,
 367        thread_store: Option<WeakEntity<ThreadStore>>,
 368        text_thread_store: Option<WeakEntity<TextThreadStore>>,
 369        initial_prompt: Option<String>,
 370        window: &mut Window,
 371        cx: &mut App,
 372    ) {
 373        let (snapshot, initial_selections, newest_selection) = editor.update(cx, |editor, cx| {
 374            let selections = editor.selections.all::<Point>(cx);
 375            let newest_selection = editor.selections.newest::<Point>(cx);
 376            (editor.snapshot(window, cx), selections, newest_selection)
 377        });
 378
 379        // Check if there is already an inline assistant that contains the
 380        // newest selection, if there is, focus it
 381        if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 382            for assist_id in &editor_assists.assist_ids {
 383                let assist = &self.assists[assist_id];
 384                let range = assist.range.to_point(&snapshot.buffer_snapshot);
 385                if range.start.row <= newest_selection.start.row
 386                    && newest_selection.end.row <= range.end.row
 387                {
 388                    self.focus_assist(*assist_id, window, cx);
 389                    return;
 390                }
 391            }
 392        }
 393
 394        let mut selections = Vec::<Selection<Point>>::new();
 395        let mut newest_selection = None;
 396        for mut selection in initial_selections {
 397            if selection.end > selection.start {
 398                selection.start.column = 0;
 399                // If the selection ends at the start of the line, we don't want to include it.
 400                if selection.end.column == 0 {
 401                    selection.end.row -= 1;
 402                }
 403                selection.end.column = snapshot
 404                    .buffer_snapshot
 405                    .line_len(MultiBufferRow(selection.end.row));
 406            } else if let Some(fold) =
 407                snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
 408            {
 409                selection.start = fold.range().start;
 410                selection.end = fold.range().end;
 411                if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot.max_row() {
 412                    let chars = snapshot
 413                        .buffer_snapshot
 414                        .chars_at(Point::new(selection.end.row + 1, 0));
 415
 416                    for c in chars {
 417                        if c == '\n' {
 418                            break;
 419                        }
 420                        if c.is_whitespace() {
 421                            continue;
 422                        }
 423                        if snapshot
 424                            .language_at(selection.end)
 425                            .is_some_and(|language| language.config().brackets.is_closing_brace(c))
 426                        {
 427                            selection.end.row += 1;
 428                            selection.end.column = snapshot
 429                                .buffer_snapshot
 430                                .line_len(MultiBufferRow(selection.end.row));
 431                        }
 432                    }
 433                }
 434            }
 435
 436            if let Some(prev_selection) = selections.last_mut()
 437                && selection.start <= prev_selection.end
 438            {
 439                prev_selection.end = selection.end;
 440                continue;
 441            }
 442
 443            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 444            if selection.id > latest_selection.id {
 445                *latest_selection = selection.clone();
 446            }
 447            selections.push(selection);
 448        }
 449        let snapshot = &snapshot.buffer_snapshot;
 450        let newest_selection = newest_selection.unwrap();
 451
 452        let mut codegen_ranges = Vec::new();
 453        for (buffer, buffer_range, excerpt_id) in
 454            snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
 455                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 456            }))
 457        {
 458            let anchor_range = Anchor::range_in_buffer(
 459                excerpt_id,
 460                buffer.remote_id(),
 461                buffer.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
 462            );
 463
 464            codegen_ranges.push(anchor_range);
 465
 466            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
 467                self.telemetry.report_assistant_event(AssistantEventData {
 468                    conversation_id: None,
 469                    kind: AssistantKind::Inline,
 470                    phase: AssistantPhase::Invoked,
 471                    message_id: None,
 472                    model: model.model.telemetry_id(),
 473                    model_provider: model.provider.id().to_string(),
 474                    response_latency: None,
 475                    error_message: None,
 476                    language_name: buffer.language().map(|language| language.name().to_proto()),
 477                });
 478            }
 479        }
 480
 481        let assist_group_id = self.next_assist_group_id.post_inc();
 482        let prompt_buffer = cx.new(|cx| {
 483            MultiBuffer::singleton(
 484                cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
 485                cx,
 486            )
 487        });
 488
 489        let mut assists = Vec::new();
 490        let mut assist_to_focus = None;
 491        for range in codegen_ranges {
 492            let assist_id = self.next_assist_id.post_inc();
 493            let codegen = cx.new(|cx| {
 494                BufferCodegen::new(
 495                    editor.read(cx).buffer().clone(),
 496                    range.clone(),
 497                    None,
 498                    context_store.clone(),
 499                    project.clone(),
 500                    prompt_store.clone(),
 501                    self.telemetry.clone(),
 502                    self.prompt_builder.clone(),
 503                    cx,
 504                )
 505            });
 506
 507            let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 508            let prompt_editor = cx.new(|cx| {
 509                PromptEditor::new_buffer(
 510                    assist_id,
 511                    editor_margins,
 512                    self.prompt_history.clone(),
 513                    prompt_buffer.clone(),
 514                    codegen.clone(),
 515                    self.fs.clone(),
 516                    context_store.clone(),
 517                    workspace.clone(),
 518                    thread_store.clone(),
 519                    text_thread_store.clone(),
 520                    window,
 521                    cx,
 522                )
 523            });
 524
 525            if assist_to_focus.is_none() {
 526                let focus_assist = if newest_selection.reversed {
 527                    range.start.to_point(snapshot) == newest_selection.start
 528                } else {
 529                    range.end.to_point(snapshot) == newest_selection.end
 530                };
 531                if focus_assist {
 532                    assist_to_focus = Some(assist_id);
 533                }
 534            }
 535
 536            let [prompt_block_id, end_block_id] =
 537                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 538
 539            assists.push((
 540                assist_id,
 541                range,
 542                prompt_editor,
 543                prompt_block_id,
 544                end_block_id,
 545            ));
 546        }
 547
 548        let editor_assists = self
 549            .assists_by_editor
 550            .entry(editor.downgrade())
 551            .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
 552        let mut assist_group = InlineAssistGroup::new();
 553        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
 554            let codegen = prompt_editor.read(cx).codegen().clone();
 555
 556            self.assists.insert(
 557                assist_id,
 558                InlineAssist::new(
 559                    assist_id,
 560                    assist_group_id,
 561                    editor,
 562                    &prompt_editor,
 563                    prompt_block_id,
 564                    end_block_id,
 565                    range,
 566                    codegen,
 567                    workspace.clone(),
 568                    window,
 569                    cx,
 570                ),
 571            );
 572            assist_group.assist_ids.push(assist_id);
 573            editor_assists.assist_ids.push(assist_id);
 574        }
 575        self.assist_groups.insert(assist_group_id, assist_group);
 576
 577        if let Some(assist_id) = assist_to_focus {
 578            self.focus_assist(assist_id, window, cx);
 579        }
 580    }
 581
 582    pub fn suggest_assist(
 583        &mut self,
 584        editor: &Entity<Editor>,
 585        mut range: Range<Anchor>,
 586        initial_prompt: String,
 587        initial_transaction_id: Option<TransactionId>,
 588        focus: bool,
 589        workspace: Entity<Workspace>,
 590        prompt_store: Option<Entity<PromptStore>>,
 591        thread_store: Option<WeakEntity<ThreadStore>>,
 592        text_thread_store: Option<WeakEntity<TextThreadStore>>,
 593        window: &mut Window,
 594        cx: &mut App,
 595    ) -> InlineAssistId {
 596        let assist_group_id = self.next_assist_group_id.post_inc();
 597        let prompt_buffer = cx.new(|cx| Buffer::local(&initial_prompt, cx));
 598        let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 599
 600        let assist_id = self.next_assist_id.post_inc();
 601
 602        let buffer = editor.read(cx).buffer().clone();
 603        {
 604            let snapshot = buffer.read(cx).read(cx);
 605            range.start = range.start.bias_left(&snapshot);
 606            range.end = range.end.bias_right(&snapshot);
 607        }
 608
 609        let project = workspace.read(cx).project().downgrade();
 610        let context_store = cx.new(|_cx| ContextStore::new(project.clone(), thread_store.clone()));
 611
 612        let codegen = cx.new(|cx| {
 613            BufferCodegen::new(
 614                editor.read(cx).buffer().clone(),
 615                range.clone(),
 616                initial_transaction_id,
 617                context_store.clone(),
 618                project,
 619                prompt_store,
 620                self.telemetry.clone(),
 621                self.prompt_builder.clone(),
 622                cx,
 623            )
 624        });
 625
 626        let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 627        let prompt_editor = cx.new(|cx| {
 628            PromptEditor::new_buffer(
 629                assist_id,
 630                editor_margins,
 631                self.prompt_history.clone(),
 632                prompt_buffer.clone(),
 633                codegen.clone(),
 634                self.fs.clone(),
 635                context_store,
 636                workspace.downgrade(),
 637                thread_store,
 638                text_thread_store,
 639                window,
 640                cx,
 641            )
 642        });
 643
 644        let [prompt_block_id, end_block_id] =
 645            self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 646
 647        let editor_assists = self
 648            .assists_by_editor
 649            .entry(editor.downgrade())
 650            .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
 651
 652        let mut assist_group = InlineAssistGroup::new();
 653        self.assists.insert(
 654            assist_id,
 655            InlineAssist::new(
 656                assist_id,
 657                assist_group_id,
 658                editor,
 659                &prompt_editor,
 660                prompt_block_id,
 661                end_block_id,
 662                range,
 663                codegen.clone(),
 664                workspace.downgrade(),
 665                window,
 666                cx,
 667            ),
 668        );
 669        assist_group.assist_ids.push(assist_id);
 670        editor_assists.assist_ids.push(assist_id);
 671        self.assist_groups.insert(assist_group_id, assist_group);
 672
 673        if focus {
 674            self.focus_assist(assist_id, window, cx);
 675        }
 676
 677        assist_id
 678    }
 679
 680    fn insert_assist_blocks(
 681        &self,
 682        editor: &Entity<Editor>,
 683        range: &Range<Anchor>,
 684        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
 685        cx: &mut App,
 686    ) -> [CustomBlockId; 2] {
 687        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 688            prompt_editor
 689                .editor
 690                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 691        });
 692        let assist_blocks = vec![
 693            BlockProperties {
 694                style: BlockStyle::Sticky,
 695                placement: BlockPlacement::Above(range.start),
 696                height: Some(prompt_editor_height),
 697                render: build_assist_editor_renderer(prompt_editor),
 698                priority: 0,
 699            },
 700            BlockProperties {
 701                style: BlockStyle::Sticky,
 702                placement: BlockPlacement::Below(range.end),
 703                height: None,
 704                render: Arc::new(|cx| {
 705                    v_flex()
 706                        .h_full()
 707                        .w_full()
 708                        .border_t_1()
 709                        .border_color(cx.theme().status().info_border)
 710                        .into_any_element()
 711                }),
 712                priority: 0,
 713            },
 714        ];
 715
 716        editor.update(cx, |editor, cx| {
 717            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 718            [block_ids[0], block_ids[1]]
 719        })
 720    }
 721
 722    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 723        let assist = &self.assists[&assist_id];
 724        let Some(decorations) = assist.decorations.as_ref() else {
 725            return;
 726        };
 727        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 728        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 729
 730        assist_group.active_assist_id = Some(assist_id);
 731        if assist_group.linked {
 732            for assist_id in &assist_group.assist_ids {
 733                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 734                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 735                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 736                    });
 737                }
 738            }
 739        }
 740
 741        assist
 742            .editor
 743            .update(cx, |editor, cx| {
 744                let scroll_top = editor.scroll_position(cx).y;
 745                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 746                let prompt_row = editor
 747                    .row_for_block(decorations.prompt_block_id, cx)
 748                    .unwrap()
 749                    .0 as f32;
 750
 751                if (scroll_top..scroll_bottom).contains(&prompt_row) {
 752                    editor_assists.scroll_lock = Some(InlineAssistScrollLock {
 753                        assist_id,
 754                        distance_from_top: prompt_row - scroll_top,
 755                    });
 756                } else {
 757                    editor_assists.scroll_lock = None;
 758                }
 759            })
 760            .ok();
 761    }
 762
 763    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 764        let assist = &self.assists[&assist_id];
 765        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 766        if assist_group.active_assist_id == Some(assist_id) {
 767            assist_group.active_assist_id = None;
 768            if assist_group.linked {
 769                for assist_id in &assist_group.assist_ids {
 770                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 771                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 772                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 773                        });
 774                    }
 775                }
 776            }
 777        }
 778    }
 779
 780    fn handle_prompt_editor_event(
 781        &mut self,
 782        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 783        event: &PromptEditorEvent,
 784        window: &mut Window,
 785        cx: &mut App,
 786    ) {
 787        let assist_id = prompt_editor.read(cx).id();
 788        match event {
 789            PromptEditorEvent::StartRequested => {
 790                self.start_assist(assist_id, window, cx);
 791            }
 792            PromptEditorEvent::StopRequested => {
 793                self.stop_assist(assist_id, cx);
 794            }
 795            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 796                self.finish_assist(assist_id, false, window, cx);
 797            }
 798            PromptEditorEvent::CancelRequested => {
 799                self.finish_assist(assist_id, true, window, cx);
 800            }
 801            PromptEditorEvent::Resized { .. } => {
 802                // This only matters for the terminal inline assistant
 803            }
 804        }
 805    }
 806
 807    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 808        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 809            return;
 810        };
 811
 812        if editor.read(cx).selections.count() == 1 {
 813            let (selection, buffer) = editor.update(cx, |editor, cx| {
 814                (
 815                    editor.selections.newest::<usize>(cx),
 816                    editor.buffer().read(cx).snapshot(cx),
 817                )
 818            });
 819            for assist_id in &editor_assists.assist_ids {
 820                let assist = &self.assists[assist_id];
 821                let assist_range = assist.range.to_offset(&buffer);
 822                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 823                {
 824                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 825                        self.dismiss_assist(*assist_id, window, cx);
 826                    } else {
 827                        self.finish_assist(*assist_id, false, window, cx);
 828                    }
 829
 830                    return;
 831                }
 832            }
 833        }
 834
 835        cx.propagate();
 836    }
 837
 838    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 839        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 840            return;
 841        };
 842
 843        if editor.read(cx).selections.count() == 1 {
 844            let (selection, buffer) = editor.update(cx, |editor, cx| {
 845                (
 846                    editor.selections.newest::<usize>(cx),
 847                    editor.buffer().read(cx).snapshot(cx),
 848                )
 849            });
 850            let mut closest_assist_fallback = None;
 851            for assist_id in &editor_assists.assist_ids {
 852                let assist = &self.assists[assist_id];
 853                let assist_range = assist.range.to_offset(&buffer);
 854                if assist.decorations.is_some() {
 855                    if assist_range.contains(&selection.start)
 856                        && assist_range.contains(&selection.end)
 857                    {
 858                        self.focus_assist(*assist_id, window, cx);
 859                        return;
 860                    } else {
 861                        let distance_from_selection = assist_range
 862                            .start
 863                            .abs_diff(selection.start)
 864                            .min(assist_range.start.abs_diff(selection.end))
 865                            + assist_range
 866                                .end
 867                                .abs_diff(selection.start)
 868                                .min(assist_range.end.abs_diff(selection.end));
 869                        match closest_assist_fallback {
 870                            Some((_, old_distance)) => {
 871                                if distance_from_selection < old_distance {
 872                                    closest_assist_fallback =
 873                                        Some((assist_id, distance_from_selection));
 874                                }
 875                            }
 876                            None => {
 877                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 878                            }
 879                        }
 880                    }
 881                }
 882            }
 883
 884            if let Some((&assist_id, _)) = closest_assist_fallback {
 885                self.focus_assist(assist_id, window, cx);
 886            }
 887        }
 888
 889        cx.propagate();
 890    }
 891
 892    fn handle_editor_release(
 893        &mut self,
 894        editor: WeakEntity<Editor>,
 895        window: &mut Window,
 896        cx: &mut App,
 897    ) {
 898        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 899            for assist_id in editor_assists.assist_ids.clone() {
 900                self.finish_assist(assist_id, true, window, cx);
 901            }
 902        }
 903    }
 904
 905    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 906        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 907            return;
 908        };
 909        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 910            return;
 911        };
 912        let assist = &self.assists[&scroll_lock.assist_id];
 913        let Some(decorations) = assist.decorations.as_ref() else {
 914            return;
 915        };
 916
 917        editor.update(cx, |editor, cx| {
 918            let scroll_position = editor.scroll_position(cx);
 919            let target_scroll_top = editor
 920                .row_for_block(decorations.prompt_block_id, cx)
 921                .unwrap()
 922                .0 as f32
 923                - scroll_lock.distance_from_top;
 924            if target_scroll_top != scroll_position.y {
 925                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 926            }
 927        });
 928    }
 929
 930    fn handle_editor_event(
 931        &mut self,
 932        editor: Entity<Editor>,
 933        event: &EditorEvent,
 934        window: &mut Window,
 935        cx: &mut App,
 936    ) {
 937        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 938            return;
 939        };
 940
 941        match event {
 942            EditorEvent::Edited { transaction_id } => {
 943                let buffer = editor.read(cx).buffer().read(cx);
 944                let edited_ranges =
 945                    buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
 946                let snapshot = buffer.snapshot(cx);
 947
 948                for assist_id in editor_assists.assist_ids.clone() {
 949                    let assist = &self.assists[&assist_id];
 950                    if matches!(
 951                        assist.codegen.read(cx).status(cx),
 952                        CodegenStatus::Error(_) | CodegenStatus::Done
 953                    ) {
 954                        let assist_range = assist.range.to_offset(&snapshot);
 955                        if edited_ranges
 956                            .iter()
 957                            .any(|range| range.overlaps(&assist_range))
 958                        {
 959                            self.finish_assist(assist_id, false, window, cx);
 960                        }
 961                    }
 962                }
 963            }
 964            EditorEvent::ScrollPositionChanged { .. } => {
 965                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 966                    let assist = &self.assists[&scroll_lock.assist_id];
 967                    if let Some(decorations) = assist.decorations.as_ref() {
 968                        let distance_from_top = editor.update(cx, |editor, cx| {
 969                            let scroll_top = editor.scroll_position(cx).y;
 970                            let prompt_row = editor
 971                                .row_for_block(decorations.prompt_block_id, cx)
 972                                .unwrap()
 973                                .0 as f32;
 974                            prompt_row - scroll_top
 975                        });
 976
 977                        if distance_from_top != scroll_lock.distance_from_top {
 978                            editor_assists.scroll_lock = None;
 979                        }
 980                    }
 981                }
 982            }
 983            EditorEvent::SelectionsChanged { .. } => {
 984                for assist_id in editor_assists.assist_ids.clone() {
 985                    let assist = &self.assists[&assist_id];
 986                    if let Some(decorations) = assist.decorations.as_ref()
 987                        && decorations
 988                            .prompt_editor
 989                            .focus_handle(cx)
 990                            .is_focused(window)
 991                    {
 992                        return;
 993                    }
 994                }
 995
 996                editor_assists.scroll_lock = None;
 997            }
 998            _ => {}
 999        }
1000    }
1001
1002    pub fn finish_assist(
1003        &mut self,
1004        assist_id: InlineAssistId,
1005        undo: bool,
1006        window: &mut Window,
1007        cx: &mut App,
1008    ) {
1009        if let Some(assist) = self.assists.get(&assist_id) {
1010            let assist_group_id = assist.group_id;
1011            if self.assist_groups[&assist_group_id].linked {
1012                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1013                    self.finish_assist(assist_id, undo, window, cx);
1014                }
1015                return;
1016            }
1017        }
1018
1019        self.dismiss_assist(assist_id, window, cx);
1020
1021        if let Some(assist) = self.assists.remove(&assist_id) {
1022            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
1023            {
1024                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1025                if entry.get().assist_ids.is_empty() {
1026                    entry.remove();
1027                }
1028            }
1029
1030            if let hash_map::Entry::Occupied(mut entry) =
1031                self.assists_by_editor.entry(assist.editor.clone())
1032            {
1033                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1034                if entry.get().assist_ids.is_empty() {
1035                    entry.remove();
1036                    if let Some(editor) = assist.editor.upgrade() {
1037                        self.update_editor_highlights(&editor, cx);
1038                    }
1039                } else {
1040                    entry.get_mut().highlight_updates.send(()).ok();
1041                }
1042            }
1043
1044            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1045            let message_id = active_alternative.read(cx).message_id.clone();
1046
1047            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1048                let language_name = assist.editor.upgrade().and_then(|editor| {
1049                    let multibuffer = editor.read(cx).buffer().read(cx);
1050                    let snapshot = multibuffer.snapshot(cx);
1051                    let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
1052                    ranges
1053                        .first()
1054                        .and_then(|(buffer, _, _)| buffer.language())
1055                        .map(|language| language.name())
1056                });
1057                report_assistant_event(
1058                    AssistantEventData {
1059                        conversation_id: None,
1060                        kind: AssistantKind::Inline,
1061                        message_id,
1062                        phase: if undo {
1063                            AssistantPhase::Rejected
1064                        } else {
1065                            AssistantPhase::Accepted
1066                        },
1067                        model: model.model.telemetry_id(),
1068                        model_provider: model.model.provider_id().to_string(),
1069                        response_latency: None,
1070                        error_message: None,
1071                        language_name: language_name.map(|name| name.to_proto()),
1072                    },
1073                    Some(self.telemetry.clone()),
1074                    cx.http_client(),
1075                    model.model.api_key(cx),
1076                    cx.background_executor(),
1077                );
1078            }
1079
1080            if undo {
1081                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1082            } else {
1083                self.confirmed_assists.insert(assist_id, active_alternative);
1084            }
1085        }
1086    }
1087
1088    fn dismiss_assist(
1089        &mut self,
1090        assist_id: InlineAssistId,
1091        window: &mut Window,
1092        cx: &mut App,
1093    ) -> bool {
1094        let Some(assist) = self.assists.get_mut(&assist_id) else {
1095            return false;
1096        };
1097        let Some(editor) = assist.editor.upgrade() else {
1098            return false;
1099        };
1100        let Some(decorations) = assist.decorations.take() else {
1101            return false;
1102        };
1103
1104        editor.update(cx, |editor, cx| {
1105            let mut to_remove = decorations.removed_line_block_ids;
1106            to_remove.insert(decorations.prompt_block_id);
1107            to_remove.insert(decorations.end_block_id);
1108            editor.remove_blocks(to_remove, None, cx);
1109        });
1110
1111        if decorations
1112            .prompt_editor
1113            .focus_handle(cx)
1114            .contains_focused(window, cx)
1115        {
1116            self.focus_next_assist(assist_id, window, cx);
1117        }
1118
1119        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1120            if editor_assists
1121                .scroll_lock
1122                .as_ref()
1123                .is_some_and(|lock| lock.assist_id == assist_id)
1124            {
1125                editor_assists.scroll_lock = None;
1126            }
1127            editor_assists.highlight_updates.send(()).ok();
1128        }
1129
1130        true
1131    }
1132
1133    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1134        let Some(assist) = self.assists.get(&assist_id) else {
1135            return;
1136        };
1137
1138        let assist_group = &self.assist_groups[&assist.group_id];
1139        let assist_ix = assist_group
1140            .assist_ids
1141            .iter()
1142            .position(|id| *id == assist_id)
1143            .unwrap();
1144        let assist_ids = assist_group
1145            .assist_ids
1146            .iter()
1147            .skip(assist_ix + 1)
1148            .chain(assist_group.assist_ids.iter().take(assist_ix));
1149
1150        for assist_id in assist_ids {
1151            let assist = &self.assists[assist_id];
1152            if assist.decorations.is_some() {
1153                self.focus_assist(*assist_id, window, cx);
1154                return;
1155            }
1156        }
1157
1158        assist
1159            .editor
1160            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1161            .ok();
1162    }
1163
1164    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1165        let Some(assist) = self.assists.get(&assist_id) else {
1166            return;
1167        };
1168
1169        if let Some(decorations) = assist.decorations.as_ref() {
1170            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1171                prompt_editor.editor.update(cx, |editor, cx| {
1172                    window.focus(&editor.focus_handle(cx));
1173                    editor.select_all(&SelectAll, window, cx);
1174                })
1175            });
1176        }
1177
1178        self.scroll_to_assist(assist_id, window, cx);
1179    }
1180
1181    pub fn scroll_to_assist(
1182        &mut self,
1183        assist_id: InlineAssistId,
1184        window: &mut Window,
1185        cx: &mut App,
1186    ) {
1187        let Some(assist) = self.assists.get(&assist_id) else {
1188            return;
1189        };
1190        let Some(editor) = assist.editor.upgrade() else {
1191            return;
1192        };
1193
1194        let position = assist.range.start;
1195        editor.update(cx, |editor, cx| {
1196            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1197                selections.select_anchor_ranges([position..position])
1198            });
1199
1200            let mut scroll_target_range = None;
1201            if let Some(decorations) = assist.decorations.as_ref() {
1202                scroll_target_range = maybe!({
1203                    let top = editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f32;
1204                    let bottom = editor.row_for_block(decorations.end_block_id, cx)?.0 as f32;
1205                    Some((top, bottom))
1206                });
1207                if scroll_target_range.is_none() {
1208                    log::error!("bug: failed to find blocks for scrolling to inline assist");
1209                }
1210            }
1211            let scroll_target_range = scroll_target_range.unwrap_or_else(|| {
1212                let snapshot = editor.snapshot(window, cx);
1213                let start_row = assist
1214                    .range
1215                    .start
1216                    .to_display_point(&snapshot.display_snapshot)
1217                    .row();
1218                let top = start_row.0 as f32;
1219                let bottom = top + 1.0;
1220                (top, bottom)
1221            });
1222            let mut scroll_target_top = scroll_target_range.0;
1223            let mut scroll_target_bottom = scroll_target_range.1;
1224
1225            scroll_target_top -= editor.vertical_scroll_margin() as f32;
1226            scroll_target_bottom += editor.vertical_scroll_margin() as f32;
1227
1228            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1229            let scroll_top = editor.scroll_position(cx).y;
1230            let scroll_bottom = scroll_top + height_in_lines;
1231
1232            if scroll_target_top < scroll_top {
1233                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1234            } else if scroll_target_bottom > scroll_bottom {
1235                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1236                    editor.set_scroll_position(
1237                        point(0., scroll_target_bottom - height_in_lines),
1238                        window,
1239                        cx,
1240                    );
1241                } else {
1242                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1243                }
1244            }
1245        });
1246    }
1247
1248    fn unlink_assist_group(
1249        &mut self,
1250        assist_group_id: InlineAssistGroupId,
1251        window: &mut Window,
1252        cx: &mut App,
1253    ) -> Vec<InlineAssistId> {
1254        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1255        assist_group.linked = false;
1256
1257        for assist_id in &assist_group.assist_ids {
1258            let assist = self.assists.get_mut(assist_id).unwrap();
1259            if let Some(editor_decorations) = assist.decorations.as_ref() {
1260                editor_decorations
1261                    .prompt_editor
1262                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1263            }
1264        }
1265        assist_group.assist_ids.clone()
1266    }
1267
1268    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1269        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1270            assist
1271        } else {
1272            return;
1273        };
1274
1275        let assist_group_id = assist.group_id;
1276        if self.assist_groups[&assist_group_id].linked {
1277            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1278                self.start_assist(assist_id, window, cx);
1279            }
1280            return;
1281        }
1282
1283        let Some(user_prompt) = assist.user_prompt(cx) else {
1284            return;
1285        };
1286
1287        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1288        self.prompt_history.push_back(user_prompt.clone());
1289        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1290            self.prompt_history.pop_front();
1291        }
1292
1293        let Some(ConfiguredModel { model, .. }) =
1294            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1295        else {
1296            return;
1297        };
1298
1299        assist
1300            .codegen
1301            .update(cx, |codegen, cx| codegen.start(model, user_prompt, cx))
1302            .log_err();
1303    }
1304
1305    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1306        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1307            assist
1308        } else {
1309            return;
1310        };
1311
1312        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1313    }
1314
1315    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1316        let mut gutter_pending_ranges = Vec::new();
1317        let mut gutter_transformed_ranges = Vec::new();
1318        let mut foreground_ranges = Vec::new();
1319        let mut inserted_row_ranges = Vec::new();
1320        let empty_assist_ids = Vec::new();
1321        let assist_ids = self
1322            .assists_by_editor
1323            .get(&editor.downgrade())
1324            .map_or(&empty_assist_ids, |editor_assists| {
1325                &editor_assists.assist_ids
1326            });
1327
1328        for assist_id in assist_ids {
1329            if let Some(assist) = self.assists.get(assist_id) {
1330                let codegen = assist.codegen.read(cx);
1331                let buffer = codegen.buffer(cx).read(cx).read(cx);
1332                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1333
1334                let pending_range =
1335                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1336                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1337                    gutter_pending_ranges.push(pending_range);
1338                }
1339
1340                if let Some(edit_position) = codegen.edit_position(cx) {
1341                    let edited_range = assist.range.start..edit_position;
1342                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1343                        gutter_transformed_ranges.push(edited_range);
1344                    }
1345                }
1346
1347                if assist.decorations.is_some() {
1348                    inserted_row_ranges
1349                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1350                }
1351            }
1352        }
1353
1354        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1355        merge_ranges(&mut foreground_ranges, &snapshot);
1356        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1357        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1358        editor.update(cx, |editor, cx| {
1359            enum GutterPendingRange {}
1360            if gutter_pending_ranges.is_empty() {
1361                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1362            } else {
1363                editor.highlight_gutter::<GutterPendingRange>(
1364                    gutter_pending_ranges,
1365                    |cx| cx.theme().status().info_background,
1366                    cx,
1367                )
1368            }
1369
1370            enum GutterTransformedRange {}
1371            if gutter_transformed_ranges.is_empty() {
1372                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1373            } else {
1374                editor.highlight_gutter::<GutterTransformedRange>(
1375                    gutter_transformed_ranges,
1376                    |cx| cx.theme().status().info,
1377                    cx,
1378                )
1379            }
1380
1381            if foreground_ranges.is_empty() {
1382                editor.clear_highlights::<InlineAssist>(cx);
1383            } else {
1384                editor.highlight_text::<InlineAssist>(
1385                    foreground_ranges,
1386                    HighlightStyle {
1387                        fade_out: Some(0.6),
1388                        ..Default::default()
1389                    },
1390                    cx,
1391                );
1392            }
1393
1394            editor.clear_row_highlights::<InlineAssist>();
1395            for row_range in inserted_row_ranges {
1396                editor.highlight_rows::<InlineAssist>(
1397                    row_range,
1398                    cx.theme().status().info_background,
1399                    Default::default(),
1400                    cx,
1401                );
1402            }
1403        });
1404    }
1405
1406    fn update_editor_blocks(
1407        &mut self,
1408        editor: &Entity<Editor>,
1409        assist_id: InlineAssistId,
1410        window: &mut Window,
1411        cx: &mut App,
1412    ) {
1413        let Some(assist) = self.assists.get_mut(&assist_id) else {
1414            return;
1415        };
1416        let Some(decorations) = assist.decorations.as_mut() else {
1417            return;
1418        };
1419
1420        let codegen = assist.codegen.read(cx);
1421        let old_snapshot = codegen.snapshot(cx);
1422        let old_buffer = codegen.old_buffer(cx);
1423        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1424
1425        editor.update(cx, |editor, cx| {
1426            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1427            editor.remove_blocks(old_blocks, None, cx);
1428
1429            let mut new_blocks = Vec::new();
1430            for (new_row, old_row_range) in deleted_row_ranges {
1431                let (_, buffer_start) = old_snapshot
1432                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1433                    .unwrap();
1434                let (_, buffer_end) = old_snapshot
1435                    .point_to_buffer_offset(Point::new(
1436                        *old_row_range.end(),
1437                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1438                    ))
1439                    .unwrap();
1440
1441                let deleted_lines_editor = cx.new(|cx| {
1442                    let multi_buffer =
1443                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1444                    multi_buffer.update(cx, |multi_buffer, cx| {
1445                        multi_buffer.push_excerpts(
1446                            old_buffer.clone(),
1447                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1448                            cx,
1449                        );
1450                    });
1451
1452                    enum DeletedLines {}
1453                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1454                    editor.disable_scrollbars_and_minimap(window, cx);
1455                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1456                    editor.set_show_wrap_guides(false, cx);
1457                    editor.set_show_gutter(false, cx);
1458                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1459                    editor.set_read_only(true);
1460                    editor.set_show_edit_predictions(Some(false), window, cx);
1461                    editor.highlight_rows::<DeletedLines>(
1462                        Anchor::min()..Anchor::max(),
1463                        cx.theme().status().deleted_background,
1464                        Default::default(),
1465                        cx,
1466                    );
1467                    editor
1468                });
1469
1470                let height =
1471                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1472                new_blocks.push(BlockProperties {
1473                    placement: BlockPlacement::Above(new_row),
1474                    height: Some(height),
1475                    style: BlockStyle::Flex,
1476                    render: Arc::new(move |cx| {
1477                        div()
1478                            .block_mouse_except_scroll()
1479                            .bg(cx.theme().status().deleted_background)
1480                            .size_full()
1481                            .h(height as f32 * cx.window.line_height())
1482                            .pl(cx.margins.gutter.full_width())
1483                            .child(deleted_lines_editor.clone())
1484                            .into_any_element()
1485                    }),
1486                    priority: 0,
1487                });
1488            }
1489
1490            decorations.removed_line_block_ids = editor
1491                .insert_blocks(new_blocks, None, cx)
1492                .into_iter()
1493                .collect();
1494        })
1495    }
1496
1497    fn resolve_inline_assist_target(
1498        workspace: &mut Workspace,
1499        agent_panel: Option<Entity<AgentPanel>>,
1500        window: &mut Window,
1501        cx: &mut App,
1502    ) -> Option<InlineAssistTarget> {
1503        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx)
1504            && terminal_panel
1505                .read(cx)
1506                .focus_handle(cx)
1507                .contains_focused(window, cx)
1508            && let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1509                pane.read(cx)
1510                    .active_item()
1511                    .and_then(|t| t.downcast::<TerminalView>())
1512            })
1513        {
1514            return Some(InlineAssistTarget::Terminal(terminal_view));
1515        }
1516
1517        let context_editor = agent_panel
1518            .and_then(|panel| panel.read(cx).active_context_editor())
1519            .and_then(|editor| {
1520                let editor = &editor.read(cx).editor().clone();
1521                if editor.read(cx).is_focused(window) {
1522                    Some(editor.clone())
1523                } else {
1524                    None
1525                }
1526            });
1527
1528        if let Some(context_editor) = context_editor {
1529            Some(InlineAssistTarget::Editor(context_editor))
1530        } else if let Some(workspace_editor) = workspace
1531            .active_item(cx)
1532            .and_then(|item| item.act_as::<Editor>(cx))
1533        {
1534            Some(InlineAssistTarget::Editor(workspace_editor))
1535        } else {
1536            workspace
1537                .active_item(cx)
1538                .and_then(|item| item.act_as::<TerminalView>(cx))
1539                .map(InlineAssistTarget::Terminal)
1540        }
1541    }
1542}
1543
1544struct EditorInlineAssists {
1545    assist_ids: Vec<InlineAssistId>,
1546    scroll_lock: Option<InlineAssistScrollLock>,
1547    highlight_updates: watch::Sender<()>,
1548    _update_highlights: Task<Result<()>>,
1549    _subscriptions: Vec<gpui::Subscription>,
1550}
1551
1552struct InlineAssistScrollLock {
1553    assist_id: InlineAssistId,
1554    distance_from_top: f32,
1555}
1556
1557impl EditorInlineAssists {
1558    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1559        let (highlight_updates_tx, mut highlight_updates_rx) = watch::channel(());
1560        Self {
1561            assist_ids: Vec::new(),
1562            scroll_lock: None,
1563            highlight_updates: highlight_updates_tx,
1564            _update_highlights: cx.spawn({
1565                let editor = editor.downgrade();
1566                async move |cx| {
1567                    while let Ok(()) = highlight_updates_rx.changed().await {
1568                        let editor = editor.upgrade().context("editor was dropped")?;
1569                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1570                            assistant.update_editor_highlights(&editor, cx);
1571                        })?;
1572                    }
1573                    Ok(())
1574                }
1575            }),
1576            _subscriptions: vec![
1577                cx.observe_release_in(editor, window, {
1578                    let editor = editor.downgrade();
1579                    |_, window, cx| {
1580                        InlineAssistant::update_global(cx, |this, cx| {
1581                            this.handle_editor_release(editor, window, cx);
1582                        })
1583                    }
1584                }),
1585                window.observe(editor, cx, move |editor, window, cx| {
1586                    InlineAssistant::update_global(cx, |this, cx| {
1587                        this.handle_editor_change(editor, window, cx)
1588                    })
1589                }),
1590                window.subscribe(editor, cx, move |editor, event, window, cx| {
1591                    InlineAssistant::update_global(cx, |this, cx| {
1592                        this.handle_editor_event(editor, event, window, cx)
1593                    })
1594                }),
1595                editor.update(cx, |editor, cx| {
1596                    let editor_handle = cx.entity().downgrade();
1597                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1598                        InlineAssistant::update_global(cx, |this, cx| {
1599                            if let Some(editor) = editor_handle.upgrade() {
1600                                this.handle_editor_newline(editor, window, cx)
1601                            }
1602                        })
1603                    })
1604                }),
1605                editor.update(cx, |editor, cx| {
1606                    let editor_handle = cx.entity().downgrade();
1607                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1608                        InlineAssistant::update_global(cx, |this, cx| {
1609                            if let Some(editor) = editor_handle.upgrade() {
1610                                this.handle_editor_cancel(editor, window, cx)
1611                            }
1612                        })
1613                    })
1614                }),
1615            ],
1616        }
1617    }
1618}
1619
1620struct InlineAssistGroup {
1621    assist_ids: Vec<InlineAssistId>,
1622    linked: bool,
1623    active_assist_id: Option<InlineAssistId>,
1624}
1625
1626impl InlineAssistGroup {
1627    fn new() -> Self {
1628        Self {
1629            assist_ids: Vec::new(),
1630            linked: true,
1631            active_assist_id: None,
1632        }
1633    }
1634}
1635
1636fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1637    let editor = editor.clone();
1638
1639    Arc::new(move |cx: &mut BlockContext| {
1640        let editor_margins = editor.read(cx).editor_margins();
1641
1642        *editor_margins.lock() = *cx.margins;
1643        editor.clone().into_any_element()
1644    })
1645}
1646
1647#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1648struct InlineAssistGroupId(usize);
1649
1650impl InlineAssistGroupId {
1651    fn post_inc(&mut self) -> InlineAssistGroupId {
1652        let id = *self;
1653        self.0 += 1;
1654        id
1655    }
1656}
1657
1658pub struct InlineAssist {
1659    group_id: InlineAssistGroupId,
1660    range: Range<Anchor>,
1661    editor: WeakEntity<Editor>,
1662    decorations: Option<InlineAssistDecorations>,
1663    codegen: Entity<BufferCodegen>,
1664    _subscriptions: Vec<Subscription>,
1665    workspace: WeakEntity<Workspace>,
1666}
1667
1668impl InlineAssist {
1669    fn new(
1670        assist_id: InlineAssistId,
1671        group_id: InlineAssistGroupId,
1672        editor: &Entity<Editor>,
1673        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1674        prompt_block_id: CustomBlockId,
1675        end_block_id: CustomBlockId,
1676        range: Range<Anchor>,
1677        codegen: Entity<BufferCodegen>,
1678        workspace: WeakEntity<Workspace>,
1679        window: &mut Window,
1680        cx: &mut App,
1681    ) -> Self {
1682        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1683        InlineAssist {
1684            group_id,
1685            editor: editor.downgrade(),
1686            decorations: Some(InlineAssistDecorations {
1687                prompt_block_id,
1688                prompt_editor: prompt_editor.clone(),
1689                removed_line_block_ids: HashSet::default(),
1690                end_block_id,
1691            }),
1692            range,
1693            codegen: codegen.clone(),
1694            workspace,
1695            _subscriptions: vec![
1696                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1697                    InlineAssistant::update_global(cx, |this, cx| {
1698                        this.handle_prompt_editor_focus_in(assist_id, cx)
1699                    })
1700                }),
1701                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1702                    InlineAssistant::update_global(cx, |this, cx| {
1703                        this.handle_prompt_editor_focus_out(assist_id, cx)
1704                    })
1705                }),
1706                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1707                    InlineAssistant::update_global(cx, |this, cx| {
1708                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1709                    })
1710                }),
1711                window.observe(&codegen, cx, {
1712                    let editor = editor.downgrade();
1713                    move |_, window, cx| {
1714                        if let Some(editor) = editor.upgrade() {
1715                            InlineAssistant::update_global(cx, |this, cx| {
1716                                if let Some(editor_assists) =
1717                                    this.assists_by_editor.get_mut(&editor.downgrade())
1718                                {
1719                                    editor_assists.highlight_updates.send(()).ok();
1720                                }
1721
1722                                this.update_editor_blocks(&editor, assist_id, window, cx);
1723                            })
1724                        }
1725                    }
1726                }),
1727                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1728                    InlineAssistant::update_global(cx, |this, cx| match event {
1729                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1730                        CodegenEvent::Finished => {
1731                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1732                                assist
1733                            } else {
1734                                return;
1735                            };
1736
1737                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx)
1738                                && assist.decorations.is_none()
1739                                && let Some(workspace) = assist.workspace.upgrade()
1740                            {
1741                                let error = format!("Inline assistant error: {}", error);
1742                                workspace.update(cx, |workspace, cx| {
1743                                    struct InlineAssistantError;
1744
1745                                    let id = NotificationId::composite::<InlineAssistantError>(
1746                                        assist_id.0,
1747                                    );
1748
1749                                    workspace.show_toast(Toast::new(id, error), cx);
1750                                })
1751                            }
1752
1753                            if assist.decorations.is_none() {
1754                                this.finish_assist(assist_id, false, window, cx);
1755                            }
1756                        }
1757                    })
1758                }),
1759            ],
1760        }
1761    }
1762
1763    fn user_prompt(&self, cx: &App) -> Option<String> {
1764        let decorations = self.decorations.as_ref()?;
1765        Some(decorations.prompt_editor.read(cx).prompt(cx))
1766    }
1767}
1768
1769struct InlineAssistDecorations {
1770    prompt_block_id: CustomBlockId,
1771    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1772    removed_line_block_ids: HashSet<CustomBlockId>,
1773    end_block_id: CustomBlockId,
1774}
1775
1776struct AssistantCodeActionProvider {
1777    editor: WeakEntity<Editor>,
1778    workspace: WeakEntity<Workspace>,
1779    thread_store: Option<WeakEntity<ThreadStore>>,
1780    text_thread_store: Option<WeakEntity<TextThreadStore>>,
1781}
1782
1783const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant2";
1784
1785impl CodeActionProvider for AssistantCodeActionProvider {
1786    fn id(&self) -> Arc<str> {
1787        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1788    }
1789
1790    fn code_actions(
1791        &self,
1792        buffer: &Entity<Buffer>,
1793        range: Range<text::Anchor>,
1794        _: &mut Window,
1795        cx: &mut App,
1796    ) -> Task<Result<Vec<CodeAction>>> {
1797        if !AgentSettings::get_global(cx).enabled {
1798            return Task::ready(Ok(Vec::new()));
1799        }
1800
1801        let snapshot = buffer.read(cx).snapshot();
1802        let mut range = range.to_point(&snapshot);
1803
1804        // Expand the range to line boundaries.
1805        range.start.column = 0;
1806        range.end.column = snapshot.line_len(range.end.row);
1807
1808        let mut has_diagnostics = false;
1809        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1810            range.start = cmp::min(range.start, diagnostic.range.start);
1811            range.end = cmp::max(range.end, diagnostic.range.end);
1812            has_diagnostics = true;
1813        }
1814        if has_diagnostics {
1815            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None)
1816                && let Some(symbol) = symbols_containing_start.last()
1817            {
1818                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1819                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1820            }
1821
1822            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None)
1823                && let Some(symbol) = symbols_containing_end.last()
1824            {
1825                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1826                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1827            }
1828
1829            Task::ready(Ok(vec![CodeAction {
1830                server_id: language::LanguageServerId(0),
1831                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1832                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1833                    title: "Fix with Assistant".into(),
1834                    ..Default::default()
1835                })),
1836                resolved: true,
1837            }]))
1838        } else {
1839            Task::ready(Ok(Vec::new()))
1840        }
1841    }
1842
1843    fn apply_code_action(
1844        &self,
1845        buffer: Entity<Buffer>,
1846        action: CodeAction,
1847        excerpt_id: ExcerptId,
1848        _push_to_history: bool,
1849        window: &mut Window,
1850        cx: &mut App,
1851    ) -> Task<Result<ProjectTransaction>> {
1852        let editor = self.editor.clone();
1853        let workspace = self.workspace.clone();
1854        let thread_store = self.thread_store.clone();
1855        let text_thread_store = self.text_thread_store.clone();
1856        let prompt_store = PromptStore::global(cx);
1857        window.spawn(cx, async move |cx| {
1858            let workspace = workspace.upgrade().context("workspace was released")?;
1859            let editor = editor.upgrade().context("editor was released")?;
1860            let range = editor
1861                .update(cx, |editor, cx| {
1862                    editor.buffer().update(cx, |multibuffer, cx| {
1863                        let buffer = buffer.read(cx);
1864                        let multibuffer_snapshot = multibuffer.read(cx);
1865
1866                        let old_context_range =
1867                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1868                        let mut new_context_range = old_context_range.clone();
1869                        if action
1870                            .range
1871                            .start
1872                            .cmp(&old_context_range.start, buffer)
1873                            .is_lt()
1874                        {
1875                            new_context_range.start = action.range.start;
1876                        }
1877                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1878                            new_context_range.end = action.range.end;
1879                        }
1880                        drop(multibuffer_snapshot);
1881
1882                        if new_context_range != old_context_range {
1883                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1884                        }
1885
1886                        let multibuffer_snapshot = multibuffer.read(cx);
1887                        Some(
1888                            multibuffer_snapshot
1889                                .anchor_in_excerpt(excerpt_id, action.range.start)?
1890                                ..multibuffer_snapshot
1891                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
1892                        )
1893                    })
1894                })?
1895                .context("invalid range")?;
1896
1897            let prompt_store = prompt_store.await.ok();
1898            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1899                let assist_id = assistant.suggest_assist(
1900                    &editor,
1901                    range,
1902                    "Fix Diagnostics".into(),
1903                    None,
1904                    true,
1905                    workspace,
1906                    prompt_store,
1907                    thread_store,
1908                    text_thread_store,
1909                    window,
1910                    cx,
1911                );
1912                assistant.start_assist(assist_id, window, cx);
1913            })?;
1914
1915            Ok(ProjectTransaction::default())
1916        })
1917    }
1918}
1919
1920fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1921    ranges.sort_unstable_by(|a, b| {
1922        a.start
1923            .cmp(&b.start, buffer)
1924            .then_with(|| b.end.cmp(&a.end, buffer))
1925    });
1926
1927    let mut ix = 0;
1928    while ix + 1 < ranges.len() {
1929        let b = ranges[ix + 1].clone();
1930        let a = &mut ranges[ix];
1931        if a.end.cmp(&b.start, buffer).is_gt() {
1932            if a.end.cmp(&b.end, buffer).is_lt() {
1933                a.end = b.end;
1934            }
1935            ranges.remove(ix + 1);
1936        } else {
1937            ix += 1;
1938        }
1939    }
1940}