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