inline_assistant.rs

   1use std::cmp;
   2use std::mem;
   3use std::ops::Range;
   4use std::rc::Rc;
   5use std::sync::Arc;
   6
   7use crate::context::load_context;
   8use crate::mention_set::MentionSet;
   9use crate::{
  10    AgentPanel,
  11    buffer_codegen::{BufferCodegen, CodegenAlternative, CodegenEvent},
  12    inline_prompt_editor::{CodegenStatus, InlineAssistId, PromptEditor, PromptEditorEvent},
  13    terminal_inline_assistant::TerminalInlineAssistant,
  14};
  15use agent::HistoryStore;
  16use agent_settings::AgentSettings;
  17use anyhow::{Context as _, Result};
  18use client::telemetry::Telemetry;
  19use collections::{HashMap, HashSet, VecDeque, hash_map};
  20use editor::EditorSnapshot;
  21use editor::MultiBufferOffset;
  22use editor::RowExt;
  23use editor::SelectionEffects;
  24use editor::scroll::ScrollOffset;
  25use editor::{
  26    Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorEvent, ExcerptId, ExcerptRange,
  27    MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint,
  28    actions::SelectAll,
  29    display_map::{
  30        BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, EditorMargins,
  31        RenderBlock, ToDisplayPoint,
  32    },
  33};
  34use fs::Fs;
  35use futures::FutureExt;
  36use gpui::{
  37    App, Context, Entity, Focusable, Global, HighlightStyle, Subscription, Task, UpdateGlobal,
  38    WeakEntity, Window, point,
  39};
  40use language::{Buffer, Point, Selection, TransactionId};
  41use language_model::{
  42    ConfigurationError, ConfiguredModel, LanguageModelRegistry, report_assistant_event,
  43};
  44use multi_buffer::MultiBufferRow;
  45use parking_lot::Mutex;
  46use project::{CodeAction, DisableAiSettings, LspAction, Project, ProjectTransaction};
  47use prompt_store::{PromptBuilder, PromptStore};
  48use settings::{Settings, SettingsStore};
  49use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
  50use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
  51use text::{OffsetRangeExt, ToPoint as _};
  52use ui::prelude::*;
  53use util::{RangeExt, ResultExt, maybe};
  54use workspace::{ItemHandle, Toast, Workspace, dock::Panel, notifications::NotificationId};
  55use zed_actions::agent::OpenSettings;
  56
  57pub fn init(
  58    fs: Arc<dyn Fs>,
  59    prompt_builder: Arc<PromptBuilder>,
  60    telemetry: Arc<Telemetry>,
  61    cx: &mut App,
  62) {
  63    cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));
  64
  65    cx.observe_global::<SettingsStore>(|cx| {
  66        if DisableAiSettings::get_global(cx).disable_ai {
  67            // Hide any active inline assist UI when AI is disabled
  68            InlineAssistant::update_global(cx, |assistant, cx| {
  69                assistant.cancel_all_active_completions(cx);
  70            });
  71        }
  72    })
  73    .detach();
  74
  75    cx.observe_new(|_workspace: &mut Workspace, window, cx| {
  76        let Some(window) = window else {
  77            return;
  78        };
  79        let workspace = cx.entity();
  80        InlineAssistant::update_global(cx, |inline_assistant, cx| {
  81            inline_assistant.register_workspace(&workspace, window, cx)
  82        });
  83    })
  84    .detach();
  85}
  86
  87const PROMPT_HISTORY_MAX_LEN: usize = 20;
  88
  89enum InlineAssistTarget {
  90    Editor(Entity<Editor>),
  91    Terminal(Entity<TerminalView>),
  92}
  93
  94pub struct InlineAssistant {
  95    next_assist_id: InlineAssistId,
  96    next_assist_group_id: InlineAssistGroupId,
  97    assists: HashMap<InlineAssistId, InlineAssist>,
  98    assists_by_editor: HashMap<WeakEntity<Editor>, EditorInlineAssists>,
  99    assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,
 100    confirmed_assists: HashMap<InlineAssistId, Entity<CodegenAlternative>>,
 101    prompt_history: VecDeque<String>,
 102    prompt_builder: Arc<PromptBuilder>,
 103    telemetry: Arc<Telemetry>,
 104    fs: Arc<dyn Fs>,
 105}
 106
 107impl Global for InlineAssistant {}
 108
 109impl InlineAssistant {
 110    pub fn new(
 111        fs: Arc<dyn Fs>,
 112        prompt_builder: Arc<PromptBuilder>,
 113        telemetry: Arc<Telemetry>,
 114    ) -> Self {
 115        Self {
 116            next_assist_id: InlineAssistId::default(),
 117            next_assist_group_id: InlineAssistGroupId::default(),
 118            assists: HashMap::default(),
 119            assists_by_editor: HashMap::default(),
 120            assist_groups: HashMap::default(),
 121            confirmed_assists: HashMap::default(),
 122            prompt_history: VecDeque::default(),
 123            prompt_builder,
 124            telemetry,
 125            fs,
 126        }
 127    }
 128
 129    pub fn register_workspace(
 130        &mut self,
 131        workspace: &Entity<Workspace>,
 132        window: &mut Window,
 133        cx: &mut App,
 134    ) {
 135        window
 136            .subscribe(workspace, cx, |workspace, event, window, cx| {
 137                Self::update_global(cx, |this, cx| {
 138                    this.handle_workspace_event(workspace, event, window, cx)
 139                });
 140            })
 141            .detach();
 142
 143        let workspace = workspace.downgrade();
 144        cx.observe_global::<SettingsStore>(move |cx| {
 145            let Some(workspace) = workspace.upgrade() else {
 146                return;
 147            };
 148            let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
 149                return;
 150            };
 151            let enabled = AgentSettings::get_global(cx).enabled(cx);
 152            terminal_panel.update(cx, |terminal_panel, cx| {
 153                terminal_panel.set_assistant_enabled(enabled, cx)
 154            });
 155        })
 156        .detach();
 157    }
 158
 159    /// Hides all active inline assists when AI is disabled
 160    pub fn cancel_all_active_completions(&mut self, cx: &mut App) {
 161        // Cancel all active completions in editors
 162        for (editor_handle, _) in self.assists_by_editor.iter() {
 163            if let Some(editor) = editor_handle.upgrade() {
 164                let windows = cx.windows();
 165                if !windows.is_empty() {
 166                    let window = windows[0];
 167                    let _ = window.update(cx, |_, window, cx| {
 168                        editor.update(cx, |editor, cx| {
 169                            if editor.has_active_edit_prediction() {
 170                                editor.cancel(&Default::default(), window, cx);
 171                            }
 172                        });
 173                    });
 174                }
 175            }
 176        }
 177    }
 178
 179    fn handle_workspace_event(
 180        &mut self,
 181        workspace: Entity<Workspace>,
 182        event: &workspace::Event,
 183        window: &mut Window,
 184        cx: &mut App,
 185    ) {
 186        match event {
 187            workspace::Event::UserSavedItem { item, .. } => {
 188                // When the user manually saves an editor, automatically accepts all finished transformations.
 189                if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx))
 190                    && let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade())
 191                {
 192                    for assist_id in editor_assists.assist_ids.clone() {
 193                        let assist = &self.assists[&assist_id];
 194                        if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
 195                            self.finish_assist(assist_id, false, window, cx)
 196                        }
 197                    }
 198                }
 199            }
 200            workspace::Event::ItemAdded { item } => {
 201                self.register_workspace_item(&workspace, item.as_ref(), window, cx);
 202            }
 203            _ => (),
 204        }
 205    }
 206
 207    fn register_workspace_item(
 208        &mut self,
 209        workspace: &Entity<Workspace>,
 210        item: &dyn ItemHandle,
 211        window: &mut Window,
 212        cx: &mut App,
 213    ) {
 214        let is_ai_enabled = !DisableAiSettings::get_global(cx).disable_ai;
 215
 216        if let Some(editor) = item.act_as::<Editor>(cx) {
 217            editor.update(cx, |editor, cx| {
 218                if is_ai_enabled {
 219                    editor.add_code_action_provider(
 220                        Rc::new(AssistantCodeActionProvider {
 221                            editor: cx.entity().downgrade(),
 222                            workspace: workspace.downgrade(),
 223                        }),
 224                        window,
 225                        cx,
 226                    );
 227
 228                    if DisableAiSettings::get_global(cx).disable_ai {
 229                        // Cancel any active edit predictions
 230                        if editor.has_active_edit_prediction() {
 231                            editor.cancel(&Default::default(), window, cx);
 232                        }
 233                    }
 234                } else {
 235                    editor.remove_code_action_provider(
 236                        ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
 237                        window,
 238                        cx,
 239                    );
 240                }
 241            });
 242        }
 243    }
 244
 245    pub fn inline_assist(
 246        workspace: &mut Workspace,
 247        action: &zed_actions::assistant::InlineAssist,
 248        window: &mut Window,
 249        cx: &mut Context<Workspace>,
 250    ) {
 251        if !AgentSettings::get_global(cx).enabled(cx) {
 252            return;
 253        }
 254
 255        let Some(inline_assist_target) = Self::resolve_inline_assist_target(
 256            workspace,
 257            workspace.panel::<AgentPanel>(cx),
 258            window,
 259            cx,
 260        ) else {
 261            return;
 262        };
 263
 264        let configuration_error = || {
 265            let model_registry = LanguageModelRegistry::read_global(cx);
 266            model_registry.configuration_error(model_registry.inline_assistant_model(), cx)
 267        };
 268
 269        let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) else {
 270            return;
 271        };
 272        let agent_panel = agent_panel.read(cx);
 273
 274        let prompt_store = agent_panel.prompt_store().as_ref().cloned();
 275        let thread_store = agent_panel.thread_store().clone();
 276
 277        let handle_assist =
 278            |window: &mut Window, cx: &mut Context<Workspace>| match inline_assist_target {
 279                InlineAssistTarget::Editor(active_editor) => {
 280                    InlineAssistant::update_global(cx, |assistant, cx| {
 281                        assistant.assist(
 282                            &active_editor,
 283                            cx.entity().downgrade(),
 284                            workspace.project().downgrade(),
 285                            thread_store,
 286                            prompt_store,
 287                            action.prompt.clone(),
 288                            window,
 289                            cx,
 290                        )
 291                    })
 292                }
 293                InlineAssistTarget::Terminal(active_terminal) => {
 294                    TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 295                        assistant.assist(
 296                            &active_terminal,
 297                            cx.entity().downgrade(),
 298                            workspace.project().downgrade(),
 299                            thread_store,
 300                            prompt_store,
 301                            action.prompt.clone(),
 302                            window,
 303                            cx,
 304                        )
 305                    })
 306                }
 307            };
 308
 309        if let Some(error) = configuration_error() {
 310            if let ConfigurationError::ProviderNotAuthenticated(provider) = error {
 311                cx.spawn(async move |_, cx| {
 312                    cx.update(|cx| provider.authenticate(cx))?.await?;
 313                    anyhow::Ok(())
 314                })
 315                .detach_and_log_err(cx);
 316
 317                if configuration_error().is_none() {
 318                    handle_assist(window, cx);
 319                }
 320            } else {
 321                cx.spawn_in(window, async move |_, cx| {
 322                    let answer = cx
 323                        .prompt(
 324                            gpui::PromptLevel::Warning,
 325                            &error.to_string(),
 326                            None,
 327                            &["Configure", "Cancel"],
 328                        )
 329                        .await
 330                        .ok();
 331                    if let Some(answer) = answer
 332                        && answer == 0
 333                    {
 334                        cx.update(|window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
 335                            .ok();
 336                    }
 337                    anyhow::Ok(())
 338                })
 339                .detach_and_log_err(cx);
 340            }
 341        } else {
 342            handle_assist(window, cx);
 343        }
 344    }
 345
 346    fn codegen_ranges(
 347        &mut self,
 348        editor: &Entity<Editor>,
 349        snapshot: &EditorSnapshot,
 350        window: &mut Window,
 351        cx: &mut App,
 352    ) -> Option<(Vec<Range<Anchor>>, Selection<Point>)> {
 353        let (initial_selections, newest_selection) = editor.update(cx, |editor, _| {
 354            (
 355                editor.selections.all::<Point>(&snapshot.display_snapshot),
 356                editor
 357                    .selections
 358                    .newest::<Point>(&snapshot.display_snapshot),
 359            )
 360        });
 361
 362        // Check if there is already an inline assistant that contains the
 363        // newest selection, if there is, focus it
 364        if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 365            for assist_id in &editor_assists.assist_ids {
 366                let assist = &self.assists[assist_id];
 367                let range = assist.range.to_point(&snapshot.buffer_snapshot());
 368                if range.start.row <= newest_selection.start.row
 369                    && newest_selection.end.row <= range.end.row
 370                {
 371                    self.focus_assist(*assist_id, window, cx);
 372                    return None;
 373                }
 374            }
 375        }
 376
 377        let mut selections = Vec::<Selection<Point>>::new();
 378        let mut newest_selection = None;
 379        for mut selection in initial_selections {
 380            if selection.end > selection.start {
 381                selection.start.column = 0;
 382                // If the selection ends at the start of the line, we don't want to include it.
 383                if selection.end.column == 0 {
 384                    selection.end.row -= 1;
 385                }
 386                selection.end.column = snapshot
 387                    .buffer_snapshot()
 388                    .line_len(MultiBufferRow(selection.end.row));
 389            } else if let Some(fold) =
 390                snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
 391            {
 392                selection.start = fold.range().start;
 393                selection.end = fold.range().end;
 394                if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot().max_row() {
 395                    let chars = snapshot
 396                        .buffer_snapshot()
 397                        .chars_at(Point::new(selection.end.row + 1, 0));
 398
 399                    for c in chars {
 400                        if c == '\n' {
 401                            break;
 402                        }
 403                        if c.is_whitespace() {
 404                            continue;
 405                        }
 406                        if snapshot
 407                            .language_at(selection.end)
 408                            .is_some_and(|language| language.config().brackets.is_closing_brace(c))
 409                        {
 410                            selection.end.row += 1;
 411                            selection.end.column = snapshot
 412                                .buffer_snapshot()
 413                                .line_len(MultiBufferRow(selection.end.row));
 414                        }
 415                    }
 416                }
 417            }
 418
 419            if let Some(prev_selection) = selections.last_mut()
 420                && selection.start <= prev_selection.end
 421            {
 422                prev_selection.end = selection.end;
 423                continue;
 424            }
 425
 426            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 427            if selection.id > latest_selection.id {
 428                *latest_selection = selection.clone();
 429            }
 430            selections.push(selection);
 431        }
 432        let snapshot = &snapshot.buffer_snapshot();
 433        let newest_selection = newest_selection.unwrap();
 434
 435        let mut codegen_ranges = Vec::new();
 436        for (buffer, buffer_range, excerpt_id) in
 437            snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
 438                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 439            }))
 440        {
 441            let anchor_range = Anchor::range_in_buffer(
 442                excerpt_id,
 443                buffer.remote_id(),
 444                buffer.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
 445            );
 446
 447            codegen_ranges.push(anchor_range);
 448
 449            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
 450                self.telemetry.report_assistant_event(AssistantEventData {
 451                    conversation_id: None,
 452                    kind: AssistantKind::Inline,
 453                    phase: AssistantPhase::Invoked,
 454                    message_id: None,
 455                    model: model.model.telemetry_id(),
 456                    model_provider: model.provider.id().to_string(),
 457                    response_latency: None,
 458                    error_message: None,
 459                    language_name: buffer.language().map(|language| language.name().to_proto()),
 460                });
 461            }
 462        }
 463
 464        Some((codegen_ranges, newest_selection))
 465    }
 466
 467    fn batch_assist(
 468        &mut self,
 469        editor: &Entity<Editor>,
 470        workspace: WeakEntity<Workspace>,
 471        project: WeakEntity<Project>,
 472        thread_store: Entity<HistoryStore>,
 473        prompt_store: Option<Entity<PromptStore>>,
 474        initial_prompt: Option<String>,
 475        window: &mut Window,
 476        codegen_ranges: &[Range<Anchor>],
 477        newest_selection: Option<Selection<Point>>,
 478        initial_transaction_id: Option<TransactionId>,
 479        cx: &mut App,
 480    ) -> Option<InlineAssistId> {
 481        let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 482
 483        let assist_group_id = self.next_assist_group_id.post_inc();
 484        let prompt_buffer = cx.new(|cx| {
 485            MultiBuffer::singleton(
 486                cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
 487                cx,
 488            )
 489        });
 490
 491        let mut assists = Vec::new();
 492        let mut assist_to_focus = None;
 493
 494        for range in codegen_ranges {
 495            let assist_id = self.next_assist_id.post_inc();
 496            let codegen = cx.new(|cx| {
 497                BufferCodegen::new(
 498                    editor.read(cx).buffer().clone(),
 499                    range.clone(),
 500                    initial_transaction_id,
 501                    self.telemetry.clone(),
 502                    self.prompt_builder.clone(),
 503                    cx,
 504                )
 505            });
 506
 507            let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 508            let prompt_editor = cx.new(|cx| {
 509                PromptEditor::new_buffer(
 510                    assist_id,
 511                    editor_margins,
 512                    self.prompt_history.clone(),
 513                    prompt_buffer.clone(),
 514                    codegen.clone(),
 515                    self.fs.clone(),
 516                    thread_store.clone(),
 517                    prompt_store.clone(),
 518                    project.clone(),
 519                    workspace.clone(),
 520                    window,
 521                    cx,
 522                )
 523            });
 524
 525            if let Some(newest_selection) = newest_selection.as_ref()
 526                && assist_to_focus.is_none()
 527            {
 528                let focus_assist = if newest_selection.reversed {
 529                    range.start.to_point(&snapshot) == newest_selection.start
 530                } else {
 531                    range.end.to_point(&snapshot) == newest_selection.end
 532                };
 533                if focus_assist {
 534                    assist_to_focus = Some(assist_id);
 535                }
 536            }
 537
 538            let [prompt_block_id, end_block_id] =
 539                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 540
 541            assists.push((
 542                assist_id,
 543                range.clone(),
 544                prompt_editor,
 545                prompt_block_id,
 546                end_block_id,
 547            ));
 548        }
 549
 550        let editor_assists = self
 551            .assists_by_editor
 552            .entry(editor.downgrade())
 553            .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
 554
 555        let assist_to_focus = if let Some(focus_id) = assist_to_focus {
 556            Some(focus_id)
 557        } else if assists.len() >= 1 {
 558            Some(assists[0].0)
 559        } else {
 560            None
 561        };
 562
 563        let mut assist_group = InlineAssistGroup::new();
 564        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
 565            let codegen = prompt_editor.read(cx).codegen().clone();
 566
 567            self.assists.insert(
 568                assist_id,
 569                InlineAssist::new(
 570                    assist_id,
 571                    assist_group_id,
 572                    editor,
 573                    &prompt_editor,
 574                    prompt_block_id,
 575                    end_block_id,
 576                    range,
 577                    codegen,
 578                    workspace.clone(),
 579                    window,
 580                    cx,
 581                ),
 582            );
 583            assist_group.assist_ids.push(assist_id);
 584            editor_assists.assist_ids.push(assist_id);
 585        }
 586
 587        self.assist_groups.insert(assist_group_id, assist_group);
 588
 589        assist_to_focus
 590    }
 591
 592    pub fn assist(
 593        &mut self,
 594        editor: &Entity<Editor>,
 595        workspace: WeakEntity<Workspace>,
 596        project: WeakEntity<Project>,
 597        thread_store: Entity<HistoryStore>,
 598        prompt_store: Option<Entity<PromptStore>>,
 599        initial_prompt: Option<String>,
 600        window: &mut Window,
 601        cx: &mut App,
 602    ) {
 603        let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 604
 605        let Some((codegen_ranges, newest_selection)) =
 606            self.codegen_ranges(editor, &snapshot, window, cx)
 607        else {
 608            return;
 609        };
 610
 611        let assist_to_focus = self.batch_assist(
 612            editor,
 613            workspace,
 614            project,
 615            thread_store,
 616            prompt_store,
 617            initial_prompt,
 618            window,
 619            &codegen_ranges,
 620            Some(newest_selection),
 621            None,
 622            cx,
 623        );
 624
 625        if let Some(assist_id) = assist_to_focus {
 626            self.focus_assist(assist_id, window, cx);
 627        }
 628    }
 629
 630    pub fn suggest_assist(
 631        &mut self,
 632        editor: &Entity<Editor>,
 633        mut range: Range<Anchor>,
 634        initial_prompt: String,
 635        initial_transaction_id: Option<TransactionId>,
 636        focus: bool,
 637        workspace: Entity<Workspace>,
 638        thread_store: Entity<HistoryStore>,
 639        prompt_store: Option<Entity<PromptStore>>,
 640        window: &mut Window,
 641        cx: &mut App,
 642    ) -> InlineAssistId {
 643        let buffer = editor.read(cx).buffer().clone();
 644        {
 645            let snapshot = buffer.read(cx).read(cx);
 646            range.start = range.start.bias_left(&snapshot);
 647            range.end = range.end.bias_right(&snapshot);
 648        }
 649
 650        let project = workspace.read(cx).project().downgrade();
 651
 652        let assist_id = self
 653            .batch_assist(
 654                editor,
 655                workspace.downgrade(),
 656                project,
 657                thread_store,
 658                prompt_store,
 659                Some(initial_prompt),
 660                window,
 661                &[range],
 662                None,
 663                initial_transaction_id,
 664                cx,
 665            )
 666            .expect("batch_assist returns an id if there's only one range");
 667
 668        if focus {
 669            self.focus_assist(assist_id, window, cx);
 670        }
 671
 672        assist_id
 673    }
 674
 675    fn insert_assist_blocks(
 676        &self,
 677        editor: &Entity<Editor>,
 678        range: &Range<Anchor>,
 679        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
 680        cx: &mut App,
 681    ) -> [CustomBlockId; 2] {
 682        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 683            prompt_editor
 684                .editor
 685                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 686        });
 687        let assist_blocks = vec![
 688            BlockProperties {
 689                style: BlockStyle::Sticky,
 690                placement: BlockPlacement::Above(range.start),
 691                height: Some(prompt_editor_height),
 692                render: build_assist_editor_renderer(prompt_editor),
 693                priority: 0,
 694            },
 695            BlockProperties {
 696                style: BlockStyle::Sticky,
 697                placement: BlockPlacement::Below(range.end),
 698                height: None,
 699                render: Arc::new(|cx| {
 700                    v_flex()
 701                        .h_full()
 702                        .w_full()
 703                        .border_t_1()
 704                        .border_color(cx.theme().status().info_border)
 705                        .into_any_element()
 706                }),
 707                priority: 0,
 708            },
 709        ];
 710
 711        editor.update(cx, |editor, cx| {
 712            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 713            [block_ids[0], block_ids[1]]
 714        })
 715    }
 716
 717    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 718        let assist = &self.assists[&assist_id];
 719        let Some(decorations) = assist.decorations.as_ref() else {
 720            return;
 721        };
 722        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 723        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 724
 725        assist_group.active_assist_id = Some(assist_id);
 726        if assist_group.linked {
 727            for assist_id in &assist_group.assist_ids {
 728                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 729                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 730                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 731                    });
 732                }
 733            }
 734        }
 735
 736        assist
 737            .editor
 738            .update(cx, |editor, cx| {
 739                let scroll_top = editor.scroll_position(cx).y;
 740                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 741                editor_assists.scroll_lock = editor
 742                    .row_for_block(decorations.prompt_block_id, cx)
 743                    .map(|row| row.as_f64())
 744                    .filter(|prompt_row| (scroll_top..scroll_bottom).contains(&prompt_row))
 745                    .map(|prompt_row| InlineAssistScrollLock {
 746                        assist_id,
 747                        distance_from_top: prompt_row - scroll_top,
 748                    });
 749            })
 750            .ok();
 751    }
 752
 753    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 754        let assist = &self.assists[&assist_id];
 755        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 756        if assist_group.active_assist_id == Some(assist_id) {
 757            assist_group.active_assist_id = None;
 758            if assist_group.linked {
 759                for assist_id in &assist_group.assist_ids {
 760                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 761                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 762                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 763                        });
 764                    }
 765                }
 766            }
 767        }
 768    }
 769
 770    fn handle_prompt_editor_event(
 771        &mut self,
 772        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 773        event: &PromptEditorEvent,
 774        window: &mut Window,
 775        cx: &mut App,
 776    ) {
 777        let assist_id = prompt_editor.read(cx).id();
 778        match event {
 779            PromptEditorEvent::StartRequested => {
 780                self.start_assist(assist_id, window, cx);
 781            }
 782            PromptEditorEvent::StopRequested => {
 783                self.stop_assist(assist_id, cx);
 784            }
 785            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 786                self.finish_assist(assist_id, false, window, cx);
 787            }
 788            PromptEditorEvent::CancelRequested => {
 789                self.finish_assist(assist_id, true, window, cx);
 790            }
 791            PromptEditorEvent::Resized { .. } => {
 792                // This only matters for the terminal inline assistant
 793            }
 794        }
 795    }
 796
 797    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 798        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 799            return;
 800        };
 801
 802        if editor.read(cx).selections.count() == 1 {
 803            let (selection, buffer) = editor.update(cx, |editor, cx| {
 804                (
 805                    editor
 806                        .selections
 807                        .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
 808                    editor.buffer().read(cx).snapshot(cx),
 809                )
 810            });
 811            for assist_id in &editor_assists.assist_ids {
 812                let assist = &self.assists[assist_id];
 813                let assist_range = assist.range.to_offset(&buffer);
 814                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 815                {
 816                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 817                        self.dismiss_assist(*assist_id, window, cx);
 818                    } else {
 819                        self.finish_assist(*assist_id, false, window, cx);
 820                    }
 821
 822                    return;
 823                }
 824            }
 825        }
 826
 827        cx.propagate();
 828    }
 829
 830    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 831        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 832            return;
 833        };
 834
 835        if editor.read(cx).selections.count() == 1 {
 836            let (selection, buffer) = editor.update(cx, |editor, cx| {
 837                (
 838                    editor
 839                        .selections
 840                        .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
 841                    editor.buffer().read(cx).snapshot(cx),
 842                )
 843            });
 844            let mut closest_assist_fallback = None;
 845            for assist_id in &editor_assists.assist_ids {
 846                let assist = &self.assists[assist_id];
 847                let assist_range = assist.range.to_offset(&buffer);
 848                if assist.decorations.is_some() {
 849                    if assist_range.contains(&selection.start)
 850                        && assist_range.contains(&selection.end)
 851                    {
 852                        self.focus_assist(*assist_id, window, cx);
 853                        return;
 854                    } else {
 855                        let distance_from_selection = assist_range
 856                            .start
 857                            .0
 858                            .abs_diff(selection.start.0)
 859                            .min(assist_range.start.0.abs_diff(selection.end.0))
 860                            + assist_range
 861                                .end
 862                                .0
 863                                .abs_diff(selection.start.0)
 864                                .min(assist_range.end.0.abs_diff(selection.end.0));
 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::<MultiBufferOffset>(*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, mention_set)) = assist.user_prompt(cx).zip(assist.mention_set(cx))
1281        else {
1282            return;
1283        };
1284
1285        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1286        self.prompt_history.push_back(user_prompt.clone());
1287        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1288            self.prompt_history.pop_front();
1289        }
1290
1291        let Some(ConfiguredModel { model, .. }) =
1292            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1293        else {
1294            return;
1295        };
1296
1297        let context_task = load_context(&mention_set, cx).shared();
1298        assist
1299            .codegen
1300            .update(cx, |codegen, cx| {
1301                codegen.start(model, user_prompt, context_task, cx)
1302            })
1303            .log_err();
1304    }
1305
1306    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1307        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1308            assist
1309        } else {
1310            return;
1311        };
1312
1313        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1314    }
1315
1316    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1317        let mut gutter_pending_ranges = Vec::new();
1318        let mut gutter_transformed_ranges = Vec::new();
1319        let mut foreground_ranges = Vec::new();
1320        let mut inserted_row_ranges = Vec::new();
1321        let empty_assist_ids = Vec::new();
1322        let assist_ids = self
1323            .assists_by_editor
1324            .get(&editor.downgrade())
1325            .map_or(&empty_assist_ids, |editor_assists| {
1326                &editor_assists.assist_ids
1327            });
1328
1329        for assist_id in assist_ids {
1330            if let Some(assist) = self.assists.get(assist_id) {
1331                let codegen = assist.codegen.read(cx);
1332                let buffer = codegen.buffer(cx).read(cx).read(cx);
1333                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1334
1335                let pending_range =
1336                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1337                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1338                    gutter_pending_ranges.push(pending_range);
1339                }
1340
1341                if let Some(edit_position) = codegen.edit_position(cx) {
1342                    let edited_range = assist.range.start..edit_position;
1343                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1344                        gutter_transformed_ranges.push(edited_range);
1345                    }
1346                }
1347
1348                if assist.decorations.is_some() {
1349                    inserted_row_ranges
1350                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1351                }
1352            }
1353        }
1354
1355        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1356        merge_ranges(&mut foreground_ranges, &snapshot);
1357        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1358        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1359        editor.update(cx, |editor, cx| {
1360            enum GutterPendingRange {}
1361            if gutter_pending_ranges.is_empty() {
1362                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1363            } else {
1364                editor.highlight_gutter::<GutterPendingRange>(
1365                    gutter_pending_ranges,
1366                    |cx| cx.theme().status().info_background,
1367                    cx,
1368                )
1369            }
1370
1371            enum GutterTransformedRange {}
1372            if gutter_transformed_ranges.is_empty() {
1373                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1374            } else {
1375                editor.highlight_gutter::<GutterTransformedRange>(
1376                    gutter_transformed_ranges,
1377                    |cx| cx.theme().status().info,
1378                    cx,
1379                )
1380            }
1381
1382            if foreground_ranges.is_empty() {
1383                editor.clear_highlights::<InlineAssist>(cx);
1384            } else {
1385                editor.highlight_text::<InlineAssist>(
1386                    foreground_ranges,
1387                    HighlightStyle {
1388                        fade_out: Some(0.6),
1389                        ..Default::default()
1390                    },
1391                    cx,
1392                );
1393            }
1394
1395            editor.clear_row_highlights::<InlineAssist>();
1396            for row_range in inserted_row_ranges {
1397                editor.highlight_rows::<InlineAssist>(
1398                    row_range,
1399                    cx.theme().status().info_background,
1400                    Default::default(),
1401                    cx,
1402                );
1403            }
1404        });
1405    }
1406
1407    fn update_editor_blocks(
1408        &mut self,
1409        editor: &Entity<Editor>,
1410        assist_id: InlineAssistId,
1411        window: &mut Window,
1412        cx: &mut App,
1413    ) {
1414        let Some(assist) = self.assists.get_mut(&assist_id) else {
1415            return;
1416        };
1417        let Some(decorations) = assist.decorations.as_mut() else {
1418            return;
1419        };
1420
1421        let codegen = assist.codegen.read(cx);
1422        let old_snapshot = codegen.snapshot(cx);
1423        let old_buffer = codegen.old_buffer(cx);
1424        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1425
1426        editor.update(cx, |editor, cx| {
1427            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1428            editor.remove_blocks(old_blocks, None, cx);
1429
1430            let mut new_blocks = Vec::new();
1431            for (new_row, old_row_range) in deleted_row_ranges {
1432                let (_, buffer_start) = old_snapshot
1433                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1434                    .unwrap();
1435                let (_, buffer_end) = old_snapshot
1436                    .point_to_buffer_offset(Point::new(
1437                        *old_row_range.end(),
1438                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1439                    ))
1440                    .unwrap();
1441
1442                let deleted_lines_editor = cx.new(|cx| {
1443                    let multi_buffer =
1444                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1445                    multi_buffer.update(cx, |multi_buffer, cx| {
1446                        multi_buffer.push_excerpts(
1447                            old_buffer.clone(),
1448                            // todo(lw): buffer_start and buffer_end might come from different snapshots!
1449                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1450                            cx,
1451                        );
1452                    });
1453
1454                    enum DeletedLines {}
1455                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1456                    editor.disable_scrollbars_and_minimap(window, cx);
1457                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1458                    editor.set_show_wrap_guides(false, cx);
1459                    editor.set_show_gutter(false, cx);
1460                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1461                    editor.set_read_only(true);
1462                    editor.set_show_edit_predictions(Some(false), window, cx);
1463                    editor.highlight_rows::<DeletedLines>(
1464                        Anchor::min()..Anchor::max(),
1465                        cx.theme().status().deleted_background,
1466                        Default::default(),
1467                        cx,
1468                    );
1469                    editor
1470                });
1471
1472                let height =
1473                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1474                new_blocks.push(BlockProperties {
1475                    placement: BlockPlacement::Above(new_row),
1476                    height: Some(height),
1477                    style: BlockStyle::Flex,
1478                    render: Arc::new(move |cx| {
1479                        div()
1480                            .block_mouse_except_scroll()
1481                            .bg(cx.theme().status().deleted_background)
1482                            .size_full()
1483                            .h(height as f32 * cx.window.line_height())
1484                            .pl(cx.margins.gutter.full_width())
1485                            .child(deleted_lines_editor.clone())
1486                            .into_any_element()
1487                    }),
1488                    priority: 0,
1489                });
1490            }
1491
1492            decorations.removed_line_block_ids = editor
1493                .insert_blocks(new_blocks, None, cx)
1494                .into_iter()
1495                .collect();
1496        })
1497    }
1498
1499    fn resolve_inline_assist_target(
1500        workspace: &mut Workspace,
1501        agent_panel: Option<Entity<AgentPanel>>,
1502        window: &mut Window,
1503        cx: &mut App,
1504    ) -> Option<InlineAssistTarget> {
1505        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx)
1506            && terminal_panel
1507                .read(cx)
1508                .focus_handle(cx)
1509                .contains_focused(window, cx)
1510            && let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1511                pane.read(cx)
1512                    .active_item()
1513                    .and_then(|t| t.downcast::<TerminalView>())
1514            })
1515        {
1516            return Some(InlineAssistTarget::Terminal(terminal_view));
1517        }
1518
1519        let text_thread_editor = agent_panel
1520            .and_then(|panel| panel.read(cx).active_text_thread_editor())
1521            .and_then(|editor| {
1522                let editor = &editor.read(cx).editor().clone();
1523                if editor.read(cx).is_focused(window) {
1524                    Some(editor.clone())
1525                } else {
1526                    None
1527                }
1528            });
1529
1530        if let Some(text_thread_editor) = text_thread_editor {
1531            Some(InlineAssistTarget::Editor(text_thread_editor))
1532        } else if let Some(workspace_editor) = workspace
1533            .active_item(cx)
1534            .and_then(|item| item.act_as::<Editor>(cx))
1535        {
1536            Some(InlineAssistTarget::Editor(workspace_editor))
1537        } else {
1538            workspace
1539                .active_item(cx)
1540                .and_then(|item| item.act_as::<TerminalView>(cx))
1541                .map(InlineAssistTarget::Terminal)
1542        }
1543    }
1544}
1545
1546struct EditorInlineAssists {
1547    assist_ids: Vec<InlineAssistId>,
1548    scroll_lock: Option<InlineAssistScrollLock>,
1549    highlight_updates: watch::Sender<()>,
1550    _update_highlights: Task<Result<()>>,
1551    _subscriptions: Vec<gpui::Subscription>,
1552}
1553
1554struct InlineAssistScrollLock {
1555    assist_id: InlineAssistId,
1556    distance_from_top: ScrollOffset,
1557}
1558
1559impl EditorInlineAssists {
1560    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1561        let (highlight_updates_tx, mut highlight_updates_rx) = watch::channel(());
1562        Self {
1563            assist_ids: Vec::new(),
1564            scroll_lock: None,
1565            highlight_updates: highlight_updates_tx,
1566            _update_highlights: cx.spawn({
1567                let editor = editor.downgrade();
1568                async move |cx| {
1569                    while let Ok(()) = highlight_updates_rx.changed().await {
1570                        let editor = editor.upgrade().context("editor was dropped")?;
1571                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1572                            assistant.update_editor_highlights(&editor, cx);
1573                        })?;
1574                    }
1575                    Ok(())
1576                }
1577            }),
1578            _subscriptions: vec![
1579                cx.observe_release_in(editor, window, {
1580                    let editor = editor.downgrade();
1581                    |_, window, cx| {
1582                        InlineAssistant::update_global(cx, |this, cx| {
1583                            this.handle_editor_release(editor, window, cx);
1584                        })
1585                    }
1586                }),
1587                window.observe(editor, cx, move |editor, window, cx| {
1588                    InlineAssistant::update_global(cx, |this, cx| {
1589                        this.handle_editor_change(editor, window, cx)
1590                    })
1591                }),
1592                window.subscribe(editor, cx, move |editor, event, window, cx| {
1593                    InlineAssistant::update_global(cx, |this, cx| {
1594                        this.handle_editor_event(editor, event, window, cx)
1595                    })
1596                }),
1597                editor.update(cx, |editor, cx| {
1598                    let editor_handle = cx.entity().downgrade();
1599                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1600                        InlineAssistant::update_global(cx, |this, cx| {
1601                            if let Some(editor) = editor_handle.upgrade() {
1602                                this.handle_editor_newline(editor, window, cx)
1603                            }
1604                        })
1605                    })
1606                }),
1607                editor.update(cx, |editor, cx| {
1608                    let editor_handle = cx.entity().downgrade();
1609                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1610                        InlineAssistant::update_global(cx, |this, cx| {
1611                            if let Some(editor) = editor_handle.upgrade() {
1612                                this.handle_editor_cancel(editor, window, cx)
1613                            }
1614                        })
1615                    })
1616                }),
1617            ],
1618        }
1619    }
1620}
1621
1622struct InlineAssistGroup {
1623    assist_ids: Vec<InlineAssistId>,
1624    linked: bool,
1625    active_assist_id: Option<InlineAssistId>,
1626}
1627
1628impl InlineAssistGroup {
1629    fn new() -> Self {
1630        Self {
1631            assist_ids: Vec::new(),
1632            linked: true,
1633            active_assist_id: None,
1634        }
1635    }
1636}
1637
1638fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1639    let editor = editor.clone();
1640
1641    Arc::new(move |cx: &mut BlockContext| {
1642        let editor_margins = editor.read(cx).editor_margins();
1643
1644        *editor_margins.lock() = *cx.margins;
1645        editor.clone().into_any_element()
1646    })
1647}
1648
1649#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1650struct InlineAssistGroupId(usize);
1651
1652impl InlineAssistGroupId {
1653    fn post_inc(&mut self) -> InlineAssistGroupId {
1654        let id = *self;
1655        self.0 += 1;
1656        id
1657    }
1658}
1659
1660pub struct InlineAssist {
1661    group_id: InlineAssistGroupId,
1662    range: Range<Anchor>,
1663    editor: WeakEntity<Editor>,
1664    decorations: Option<InlineAssistDecorations>,
1665    codegen: Entity<BufferCodegen>,
1666    _subscriptions: Vec<Subscription>,
1667    workspace: WeakEntity<Workspace>,
1668}
1669
1670impl InlineAssist {
1671    fn new(
1672        assist_id: InlineAssistId,
1673        group_id: InlineAssistGroupId,
1674        editor: &Entity<Editor>,
1675        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1676        prompt_block_id: CustomBlockId,
1677        end_block_id: CustomBlockId,
1678        range: Range<Anchor>,
1679        codegen: Entity<BufferCodegen>,
1680        workspace: WeakEntity<Workspace>,
1681        window: &mut Window,
1682        cx: &mut App,
1683    ) -> Self {
1684        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1685        InlineAssist {
1686            group_id,
1687            editor: editor.downgrade(),
1688            decorations: Some(InlineAssistDecorations {
1689                prompt_block_id,
1690                prompt_editor: prompt_editor.clone(),
1691                removed_line_block_ids: HashSet::default(),
1692                end_block_id,
1693            }),
1694            range,
1695            codegen: codegen.clone(),
1696            workspace,
1697            _subscriptions: vec![
1698                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1699                    InlineAssistant::update_global(cx, |this, cx| {
1700                        this.handle_prompt_editor_focus_in(assist_id, cx)
1701                    })
1702                }),
1703                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1704                    InlineAssistant::update_global(cx, |this, cx| {
1705                        this.handle_prompt_editor_focus_out(assist_id, cx)
1706                    })
1707                }),
1708                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1709                    InlineAssistant::update_global(cx, |this, cx| {
1710                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1711                    })
1712                }),
1713                window.observe(&codegen, cx, {
1714                    let editor = editor.downgrade();
1715                    move |_, window, cx| {
1716                        if let Some(editor) = editor.upgrade() {
1717                            InlineAssistant::update_global(cx, |this, cx| {
1718                                if let Some(editor_assists) =
1719                                    this.assists_by_editor.get_mut(&editor.downgrade())
1720                                {
1721                                    editor_assists.highlight_updates.send(()).ok();
1722                                }
1723
1724                                this.update_editor_blocks(&editor, assist_id, window, cx);
1725                            })
1726                        }
1727                    }
1728                }),
1729                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1730                    InlineAssistant::update_global(cx, |this, cx| match event {
1731                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1732                        CodegenEvent::Finished => {
1733                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1734                                assist
1735                            } else {
1736                                return;
1737                            };
1738
1739                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx)
1740                                && assist.decorations.is_none()
1741                                && let Some(workspace) = assist.workspace.upgrade()
1742                            {
1743                                let error = format!("Inline assistant error: {}", error);
1744                                workspace.update(cx, |workspace, cx| {
1745                                    struct InlineAssistantError;
1746
1747                                    let id = NotificationId::composite::<InlineAssistantError>(
1748                                        assist_id.0,
1749                                    );
1750
1751                                    workspace.show_toast(Toast::new(id, error), cx);
1752                                })
1753                            }
1754
1755                            if assist.decorations.is_none() {
1756                                this.finish_assist(assist_id, false, window, cx);
1757                            }
1758                        }
1759                    })
1760                }),
1761            ],
1762        }
1763    }
1764
1765    fn user_prompt(&self, cx: &App) -> Option<String> {
1766        let decorations = self.decorations.as_ref()?;
1767        Some(decorations.prompt_editor.read(cx).prompt(cx))
1768    }
1769
1770    fn mention_set(&self, cx: &App) -> Option<Entity<MentionSet>> {
1771        let decorations = self.decorations.as_ref()?;
1772        Some(decorations.prompt_editor.read(cx).mention_set().clone())
1773    }
1774}
1775
1776struct InlineAssistDecorations {
1777    prompt_block_id: CustomBlockId,
1778    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1779    removed_line_block_ids: HashSet<CustomBlockId>,
1780    end_block_id: CustomBlockId,
1781}
1782
1783struct AssistantCodeActionProvider {
1784    editor: WeakEntity<Editor>,
1785    workspace: WeakEntity<Workspace>,
1786}
1787
1788const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant";
1789
1790impl CodeActionProvider for AssistantCodeActionProvider {
1791    fn id(&self) -> Arc<str> {
1792        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1793    }
1794
1795    fn code_actions(
1796        &self,
1797        buffer: &Entity<Buffer>,
1798        range: Range<text::Anchor>,
1799        _: &mut Window,
1800        cx: &mut App,
1801    ) -> Task<Result<Vec<CodeAction>>> {
1802        if !AgentSettings::get_global(cx).enabled(cx) {
1803            return Task::ready(Ok(Vec::new()));
1804        }
1805
1806        let snapshot = buffer.read(cx).snapshot();
1807        let mut range = range.to_point(&snapshot);
1808
1809        // Expand the range to line boundaries.
1810        range.start.column = 0;
1811        range.end.column = snapshot.line_len(range.end.row);
1812
1813        let mut has_diagnostics = false;
1814        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1815            range.start = cmp::min(range.start, diagnostic.range.start);
1816            range.end = cmp::max(range.end, diagnostic.range.end);
1817            has_diagnostics = true;
1818        }
1819        if has_diagnostics {
1820            let symbols_containing_start = snapshot.symbols_containing(range.start, None);
1821            if let Some(symbol) = symbols_containing_start.last() {
1822                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1823                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1824            }
1825            let symbols_containing_end = snapshot.symbols_containing(range.end, None);
1826            if let Some(symbol) = symbols_containing_end.last() {
1827                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1828                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1829            }
1830
1831            Task::ready(Ok(vec![CodeAction {
1832                server_id: language::LanguageServerId(0),
1833                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1834                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1835                    title: "Fix with Assistant".into(),
1836                    ..Default::default()
1837                })),
1838                resolved: true,
1839            }]))
1840        } else {
1841            Task::ready(Ok(Vec::new()))
1842        }
1843    }
1844
1845    fn apply_code_action(
1846        &self,
1847        buffer: Entity<Buffer>,
1848        action: CodeAction,
1849        excerpt_id: ExcerptId,
1850        _push_to_history: bool,
1851        window: &mut Window,
1852        cx: &mut App,
1853    ) -> Task<Result<ProjectTransaction>> {
1854        let editor = self.editor.clone();
1855        let workspace = self.workspace.clone();
1856        let prompt_store = PromptStore::global(cx);
1857        window.spawn(cx, async move |cx| {
1858            let workspace = workspace.upgrade().context("workspace was released")?;
1859            let thread_store = cx.update(|_window, cx| {
1860                anyhow::Ok(
1861                    workspace
1862                        .read(cx)
1863                        .panel::<AgentPanel>(cx)
1864                        .context("missing agent panel")?
1865                        .read(cx)
1866                        .thread_store()
1867                        .clone(),
1868                )
1869            })??;
1870            let editor = editor.upgrade().context("editor was released")?;
1871            let range = editor
1872                .update(cx, |editor, cx| {
1873                    editor.buffer().update(cx, |multibuffer, cx| {
1874                        let buffer = buffer.read(cx);
1875                        let multibuffer_snapshot = multibuffer.read(cx);
1876
1877                        let old_context_range =
1878                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1879                        let mut new_context_range = old_context_range.clone();
1880                        if action
1881                            .range
1882                            .start
1883                            .cmp(&old_context_range.start, buffer)
1884                            .is_lt()
1885                        {
1886                            new_context_range.start = action.range.start;
1887                        }
1888                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1889                            new_context_range.end = action.range.end;
1890                        }
1891                        drop(multibuffer_snapshot);
1892
1893                        if new_context_range != old_context_range {
1894                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1895                        }
1896
1897                        let multibuffer_snapshot = multibuffer.read(cx);
1898                        multibuffer_snapshot.anchor_range_in_excerpt(excerpt_id, action.range)
1899                    })
1900                })?
1901                .context("invalid range")?;
1902
1903            let prompt_store = prompt_store.await.ok();
1904            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1905                let assist_id = assistant.suggest_assist(
1906                    &editor,
1907                    range,
1908                    "Fix Diagnostics".into(),
1909                    None,
1910                    true,
1911                    workspace,
1912                    thread_store,
1913                    prompt_store,
1914                    window,
1915                    cx,
1916                );
1917                assistant.start_assist(assist_id, window, cx);
1918            })?;
1919
1920            Ok(ProjectTransaction::default())
1921        })
1922    }
1923}
1924
1925fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1926    ranges.sort_unstable_by(|a, b| {
1927        a.start
1928            .cmp(&b.start, buffer)
1929            .then_with(|| b.end.cmp(&a.end, buffer))
1930    });
1931
1932    let mut ix = 0;
1933    while ix + 1 < ranges.len() {
1934        let b = ranges[ix + 1].clone();
1935        let a = &mut ranges[ix];
1936        if a.end.cmp(&b.start, buffer).is_gt() {
1937            if a.end.cmp(&b.end, buffer).is_lt() {
1938                a.end = b.end;
1939            }
1940            ranges.remove(ix + 1);
1941        } else {
1942            ix += 1;
1943        }
1944    }
1945}