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