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