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.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
 444            );
 445
 446            codegen_ranges.push(anchor_range);
 447
 448            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
 449                self.telemetry.report_assistant_event(AssistantEventData {
 450                    conversation_id: None,
 451                    kind: AssistantKind::Inline,
 452                    phase: AssistantPhase::Invoked,
 453                    message_id: None,
 454                    model: model.model.telemetry_id(),
 455                    model_provider: model.provider.id().to_string(),
 456                    response_latency: None,
 457                    error_message: None,
 458                    language_name: buffer.language().map(|language| language.name().to_proto()),
 459                });
 460            }
 461        }
 462
 463        Some((codegen_ranges, newest_selection))
 464    }
 465
 466    fn batch_assist(
 467        &mut self,
 468        editor: &Entity<Editor>,
 469        workspace: WeakEntity<Workspace>,
 470        project: WeakEntity<Project>,
 471        thread_store: Entity<HistoryStore>,
 472        prompt_store: Option<Entity<PromptStore>>,
 473        initial_prompt: Option<String>,
 474        window: &mut Window,
 475        codegen_ranges: &[Range<Anchor>],
 476        newest_selection: Option<Selection<Point>>,
 477        initial_transaction_id: Option<TransactionId>,
 478        cx: &mut App,
 479    ) -> Option<InlineAssistId> {
 480        let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 481
 482        let assist_group_id = self.next_assist_group_id.post_inc();
 483        let prompt_buffer = cx.new(|cx| {
 484            MultiBuffer::singleton(
 485                cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
 486                cx,
 487            )
 488        });
 489
 490        let mut assists = Vec::new();
 491        let mut assist_to_focus = None;
 492
 493        for range in codegen_ranges {
 494            let assist_id = self.next_assist_id.post_inc();
 495            let codegen = cx.new(|cx| {
 496                BufferCodegen::new(
 497                    editor.read(cx).buffer().clone(),
 498                    range.clone(),
 499                    initial_transaction_id,
 500                    self.telemetry.clone(),
 501                    self.prompt_builder.clone(),
 502                    cx,
 503                )
 504            });
 505
 506            let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 507            let prompt_editor = cx.new(|cx| {
 508                PromptEditor::new_buffer(
 509                    assist_id,
 510                    editor_margins,
 511                    self.prompt_history.clone(),
 512                    prompt_buffer.clone(),
 513                    codegen.clone(),
 514                    self.fs.clone(),
 515                    thread_store.clone(),
 516                    prompt_store.clone(),
 517                    project.clone(),
 518                    workspace.clone(),
 519                    window,
 520                    cx,
 521                )
 522            });
 523
 524            if let Some(newest_selection) = newest_selection.as_ref()
 525                && assist_to_focus.is_none()
 526            {
 527                let focus_assist = if newest_selection.reversed {
 528                    range.start.to_point(&snapshot) == newest_selection.start
 529                } else {
 530                    range.end.to_point(&snapshot) == newest_selection.end
 531                };
 532                if focus_assist {
 533                    assist_to_focus = Some(assist_id);
 534                }
 535            }
 536
 537            let [prompt_block_id, end_block_id] =
 538                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 539
 540            assists.push((
 541                assist_id,
 542                range.clone(),
 543                prompt_editor,
 544                prompt_block_id,
 545                end_block_id,
 546            ));
 547        }
 548
 549        let editor_assists = self
 550            .assists_by_editor
 551            .entry(editor.downgrade())
 552            .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
 553
 554        let assist_to_focus = if let Some(focus_id) = assist_to_focus {
 555            Some(focus_id)
 556        } else if assists.len() >= 1 {
 557            Some(assists[0].0)
 558        } else {
 559            None
 560        };
 561
 562        let mut assist_group = InlineAssistGroup::new();
 563        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
 564            let codegen = prompt_editor.read(cx).codegen().clone();
 565
 566            self.assists.insert(
 567                assist_id,
 568                InlineAssist::new(
 569                    assist_id,
 570                    assist_group_id,
 571                    editor,
 572                    &prompt_editor,
 573                    prompt_block_id,
 574                    end_block_id,
 575                    range,
 576                    codegen,
 577                    workspace.clone(),
 578                    window,
 579                    cx,
 580                ),
 581            );
 582            assist_group.assist_ids.push(assist_id);
 583            editor_assists.assist_ids.push(assist_id);
 584        }
 585
 586        self.assist_groups.insert(assist_group_id, assist_group);
 587
 588        assist_to_focus
 589    }
 590
 591    pub fn assist(
 592        &mut self,
 593        editor: &Entity<Editor>,
 594        workspace: WeakEntity<Workspace>,
 595        project: WeakEntity<Project>,
 596        thread_store: Entity<HistoryStore>,
 597        prompt_store: Option<Entity<PromptStore>>,
 598        initial_prompt: Option<String>,
 599        window: &mut Window,
 600        cx: &mut App,
 601    ) {
 602        let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 603
 604        let Some((codegen_ranges, newest_selection)) =
 605            self.codegen_ranges(editor, &snapshot, window, cx)
 606        else {
 607            return;
 608        };
 609
 610        let assist_to_focus = self.batch_assist(
 611            editor,
 612            workspace,
 613            project,
 614            thread_store,
 615            prompt_store,
 616            initial_prompt,
 617            window,
 618            &codegen_ranges,
 619            Some(newest_selection),
 620            None,
 621            cx,
 622        );
 623
 624        if let Some(assist_id) = assist_to_focus {
 625            self.focus_assist(assist_id, window, cx);
 626        }
 627    }
 628
 629    pub fn suggest_assist(
 630        &mut self,
 631        editor: &Entity<Editor>,
 632        mut range: Range<Anchor>,
 633        initial_prompt: String,
 634        initial_transaction_id: Option<TransactionId>,
 635        focus: bool,
 636        workspace: Entity<Workspace>,
 637        thread_store: Entity<HistoryStore>,
 638        prompt_store: Option<Entity<PromptStore>>,
 639        window: &mut Window,
 640        cx: &mut App,
 641    ) -> InlineAssistId {
 642        let buffer = editor.read(cx).buffer().clone();
 643        {
 644            let snapshot = buffer.read(cx).read(cx);
 645            range.start = range.start.bias_left(&snapshot);
 646            range.end = range.end.bias_right(&snapshot);
 647        }
 648
 649        let project = workspace.read(cx).project().downgrade();
 650
 651        let assist_id = self
 652            .batch_assist(
 653                editor,
 654                workspace.downgrade(),
 655                project,
 656                thread_store,
 657                prompt_store,
 658                Some(initial_prompt),
 659                window,
 660                &[range],
 661                None,
 662                initial_transaction_id,
 663                cx,
 664            )
 665            .expect("batch_assist returns an id if there's only one range");
 666
 667        if focus {
 668            self.focus_assist(assist_id, window, cx);
 669        }
 670
 671        assist_id
 672    }
 673
 674    fn insert_assist_blocks(
 675        &self,
 676        editor: &Entity<Editor>,
 677        range: &Range<Anchor>,
 678        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
 679        cx: &mut App,
 680    ) -> [CustomBlockId; 2] {
 681        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 682            prompt_editor
 683                .editor
 684                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 685        });
 686        let assist_blocks = vec![
 687            BlockProperties {
 688                style: BlockStyle::Sticky,
 689                placement: BlockPlacement::Above(range.start),
 690                height: Some(prompt_editor_height),
 691                render: build_assist_editor_renderer(prompt_editor),
 692                priority: 0,
 693            },
 694            BlockProperties {
 695                style: BlockStyle::Sticky,
 696                placement: BlockPlacement::Below(range.end),
 697                height: None,
 698                render: Arc::new(|cx| {
 699                    v_flex()
 700                        .h_full()
 701                        .w_full()
 702                        .border_t_1()
 703                        .border_color(cx.theme().status().info_border)
 704                        .into_any_element()
 705                }),
 706                priority: 0,
 707            },
 708        ];
 709
 710        editor.update(cx, |editor, cx| {
 711            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 712            [block_ids[0], block_ids[1]]
 713        })
 714    }
 715
 716    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 717        let assist = &self.assists[&assist_id];
 718        let Some(decorations) = assist.decorations.as_ref() else {
 719            return;
 720        };
 721        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 722        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 723
 724        assist_group.active_assist_id = Some(assist_id);
 725        if assist_group.linked {
 726            for assist_id in &assist_group.assist_ids {
 727                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 728                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 729                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 730                    });
 731                }
 732            }
 733        }
 734
 735        assist
 736            .editor
 737            .update(cx, |editor, cx| {
 738                let scroll_top = editor.scroll_position(cx).y;
 739                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 740                editor_assists.scroll_lock = editor
 741                    .row_for_block(decorations.prompt_block_id, cx)
 742                    .map(|row| row.as_f64())
 743                    .filter(|prompt_row| (scroll_top..scroll_bottom).contains(&prompt_row))
 744                    .map(|prompt_row| InlineAssistScrollLock {
 745                        assist_id,
 746                        distance_from_top: prompt_row - scroll_top,
 747                    });
 748            })
 749            .ok();
 750    }
 751
 752    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 753        let assist = &self.assists[&assist_id];
 754        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 755        if assist_group.active_assist_id == Some(assist_id) {
 756            assist_group.active_assist_id = None;
 757            if assist_group.linked {
 758                for assist_id in &assist_group.assist_ids {
 759                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 760                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 761                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 762                        });
 763                    }
 764                }
 765            }
 766        }
 767    }
 768
 769    fn handle_prompt_editor_event(
 770        &mut self,
 771        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 772        event: &PromptEditorEvent,
 773        window: &mut Window,
 774        cx: &mut App,
 775    ) {
 776        let assist_id = prompt_editor.read(cx).id();
 777        match event {
 778            PromptEditorEvent::StartRequested => {
 779                self.start_assist(assist_id, window, cx);
 780            }
 781            PromptEditorEvent::StopRequested => {
 782                self.stop_assist(assist_id, cx);
 783            }
 784            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 785                self.finish_assist(assist_id, false, window, cx);
 786            }
 787            PromptEditorEvent::CancelRequested => {
 788                self.finish_assist(assist_id, true, window, cx);
 789            }
 790            PromptEditorEvent::Resized { .. } => {
 791                // This only matters for the terminal inline assistant
 792            }
 793        }
 794    }
 795
 796    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 797        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 798            return;
 799        };
 800
 801        if editor.read(cx).selections.count() == 1 {
 802            let (selection, buffer) = editor.update(cx, |editor, cx| {
 803                (
 804                    editor
 805                        .selections
 806                        .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
 807                    editor.buffer().read(cx).snapshot(cx),
 808                )
 809            });
 810            for assist_id in &editor_assists.assist_ids {
 811                let assist = &self.assists[assist_id];
 812                let assist_range = assist.range.to_offset(&buffer);
 813                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 814                {
 815                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 816                        self.dismiss_assist(*assist_id, window, cx);
 817                    } else {
 818                        self.finish_assist(*assist_id, false, window, cx);
 819                    }
 820
 821                    return;
 822                }
 823            }
 824        }
 825
 826        cx.propagate();
 827    }
 828
 829    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 830        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 831            return;
 832        };
 833
 834        if editor.read(cx).selections.count() == 1 {
 835            let (selection, buffer) = editor.update(cx, |editor, cx| {
 836                (
 837                    editor
 838                        .selections
 839                        .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
 840                    editor.buffer().read(cx).snapshot(cx),
 841                )
 842            });
 843            let mut closest_assist_fallback = None;
 844            for assist_id in &editor_assists.assist_ids {
 845                let assist = &self.assists[assist_id];
 846                let assist_range = assist.range.to_offset(&buffer);
 847                if assist.decorations.is_some() {
 848                    if assist_range.contains(&selection.start)
 849                        && assist_range.contains(&selection.end)
 850                    {
 851                        self.focus_assist(*assist_id, window, cx);
 852                        return;
 853                    } else {
 854                        let distance_from_selection = assist_range
 855                            .start
 856                            .0
 857                            .abs_diff(selection.start.0)
 858                            .min(assist_range.start.0.abs_diff(selection.end.0))
 859                            + assist_range
 860                                .end
 861                                .0
 862                                .abs_diff(selection.start.0)
 863                                .min(assist_range.end.0.abs_diff(selection.end.0));
 864                        match closest_assist_fallback {
 865                            Some((_, old_distance)) => {
 866                                if distance_from_selection < old_distance {
 867                                    closest_assist_fallback =
 868                                        Some((assist_id, distance_from_selection));
 869                                }
 870                            }
 871                            None => {
 872                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 873                            }
 874                        }
 875                    }
 876                }
 877            }
 878
 879            if let Some((&assist_id, _)) = closest_assist_fallback {
 880                self.focus_assist(assist_id, window, cx);
 881            }
 882        }
 883
 884        cx.propagate();
 885    }
 886
 887    fn handle_editor_release(
 888        &mut self,
 889        editor: WeakEntity<Editor>,
 890        window: &mut Window,
 891        cx: &mut App,
 892    ) {
 893        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 894            for assist_id in editor_assists.assist_ids.clone() {
 895                self.finish_assist(assist_id, true, window, cx);
 896            }
 897        }
 898    }
 899
 900    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 901        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 902            return;
 903        };
 904        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 905            return;
 906        };
 907        let assist = &self.assists[&scroll_lock.assist_id];
 908        let Some(decorations) = assist.decorations.as_ref() else {
 909            return;
 910        };
 911
 912        editor.update(cx, |editor, cx| {
 913            let scroll_position = editor.scroll_position(cx);
 914            let target_scroll_top = editor
 915                .row_for_block(decorations.prompt_block_id, cx)?
 916                .as_f64()
 917                - scroll_lock.distance_from_top;
 918            if target_scroll_top != scroll_position.y {
 919                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 920            }
 921            Some(())
 922        });
 923    }
 924
 925    fn handle_editor_event(
 926        &mut self,
 927        editor: Entity<Editor>,
 928        event: &EditorEvent,
 929        window: &mut Window,
 930        cx: &mut App,
 931    ) {
 932        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 933            return;
 934        };
 935
 936        match event {
 937            EditorEvent::Edited { transaction_id } => {
 938                let buffer = editor.read(cx).buffer().read(cx);
 939                let edited_ranges =
 940                    buffer.edited_ranges_for_transaction::<MultiBufferOffset>(*transaction_id, cx);
 941                let snapshot = buffer.snapshot(cx);
 942
 943                for assist_id in editor_assists.assist_ids.clone() {
 944                    let assist = &self.assists[&assist_id];
 945                    if matches!(
 946                        assist.codegen.read(cx).status(cx),
 947                        CodegenStatus::Error(_) | CodegenStatus::Done
 948                    ) {
 949                        let assist_range = assist.range.to_offset(&snapshot);
 950                        if edited_ranges
 951                            .iter()
 952                            .any(|range| range.overlaps(&assist_range))
 953                        {
 954                            self.finish_assist(assist_id, false, window, cx);
 955                        }
 956                    }
 957                }
 958            }
 959            EditorEvent::ScrollPositionChanged { .. } => {
 960                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 961                    let assist = &self.assists[&scroll_lock.assist_id];
 962                    if let Some(decorations) = assist.decorations.as_ref() {
 963                        let distance_from_top = editor.update(cx, |editor, cx| {
 964                            let scroll_top = editor.scroll_position(cx).y;
 965                            let prompt_row = editor
 966                                .row_for_block(decorations.prompt_block_id, cx)?
 967                                .0 as ScrollOffset;
 968                            Some(prompt_row - scroll_top)
 969                        });
 970
 971                        if distance_from_top.is_none_or(|distance_from_top| {
 972                            distance_from_top != scroll_lock.distance_from_top
 973                        }) {
 974                            editor_assists.scroll_lock = None;
 975                        }
 976                    }
 977                }
 978            }
 979            EditorEvent::SelectionsChanged { .. } => {
 980                for assist_id in editor_assists.assist_ids.clone() {
 981                    let assist = &self.assists[&assist_id];
 982                    if let Some(decorations) = assist.decorations.as_ref()
 983                        && decorations
 984                            .prompt_editor
 985                            .focus_handle(cx)
 986                            .is_focused(window)
 987                    {
 988                        return;
 989                    }
 990                }
 991
 992                editor_assists.scroll_lock = None;
 993            }
 994            _ => {}
 995        }
 996    }
 997
 998    pub fn finish_assist(
 999        &mut self,
1000        assist_id: InlineAssistId,
1001        undo: bool,
1002        window: &mut Window,
1003        cx: &mut App,
1004    ) {
1005        if let Some(assist) = self.assists.get(&assist_id) {
1006            let assist_group_id = assist.group_id;
1007            if self.assist_groups[&assist_group_id].linked {
1008                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1009                    self.finish_assist(assist_id, undo, window, cx);
1010                }
1011                return;
1012            }
1013        }
1014
1015        self.dismiss_assist(assist_id, window, cx);
1016
1017        if let Some(assist) = self.assists.remove(&assist_id) {
1018            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
1019            {
1020                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1021                if entry.get().assist_ids.is_empty() {
1022                    entry.remove();
1023                }
1024            }
1025
1026            if let hash_map::Entry::Occupied(mut entry) =
1027                self.assists_by_editor.entry(assist.editor.clone())
1028            {
1029                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1030                if entry.get().assist_ids.is_empty() {
1031                    entry.remove();
1032                    if let Some(editor) = assist.editor.upgrade() {
1033                        self.update_editor_highlights(&editor, cx);
1034                    }
1035                } else {
1036                    entry.get_mut().highlight_updates.send(()).ok();
1037                }
1038            }
1039
1040            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1041            let message_id = active_alternative.read(cx).message_id.clone();
1042
1043            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1044                let language_name = assist.editor.upgrade().and_then(|editor| {
1045                    let multibuffer = editor.read(cx).buffer().read(cx);
1046                    let snapshot = multibuffer.snapshot(cx);
1047                    let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
1048                    ranges
1049                        .first()
1050                        .and_then(|(buffer, _, _)| buffer.language())
1051                        .map(|language| language.name())
1052                });
1053                report_assistant_event(
1054                    AssistantEventData {
1055                        conversation_id: None,
1056                        kind: AssistantKind::Inline,
1057                        message_id,
1058                        phase: if undo {
1059                            AssistantPhase::Rejected
1060                        } else {
1061                            AssistantPhase::Accepted
1062                        },
1063                        model: model.model.telemetry_id(),
1064                        model_provider: model.model.provider_id().to_string(),
1065                        response_latency: None,
1066                        error_message: None,
1067                        language_name: language_name.map(|name| name.to_proto()),
1068                    },
1069                    Some(self.telemetry.clone()),
1070                    cx.http_client(),
1071                    model.model.api_key(cx),
1072                    cx.background_executor(),
1073                );
1074            }
1075
1076            if undo {
1077                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1078            } else {
1079                self.confirmed_assists.insert(assist_id, active_alternative);
1080            }
1081        }
1082    }
1083
1084    fn dismiss_assist(
1085        &mut self,
1086        assist_id: InlineAssistId,
1087        window: &mut Window,
1088        cx: &mut App,
1089    ) -> bool {
1090        let Some(assist) = self.assists.get_mut(&assist_id) else {
1091            return false;
1092        };
1093        let Some(editor) = assist.editor.upgrade() else {
1094            return false;
1095        };
1096        let Some(decorations) = assist.decorations.take() else {
1097            return false;
1098        };
1099
1100        editor.update(cx, |editor, cx| {
1101            let mut to_remove = decorations.removed_line_block_ids;
1102            to_remove.insert(decorations.prompt_block_id);
1103            to_remove.insert(decorations.end_block_id);
1104            editor.remove_blocks(to_remove, None, cx);
1105        });
1106
1107        if decorations
1108            .prompt_editor
1109            .focus_handle(cx)
1110            .contains_focused(window, cx)
1111        {
1112            self.focus_next_assist(assist_id, window, cx);
1113        }
1114
1115        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1116            if editor_assists
1117                .scroll_lock
1118                .as_ref()
1119                .is_some_and(|lock| lock.assist_id == assist_id)
1120            {
1121                editor_assists.scroll_lock = None;
1122            }
1123            editor_assists.highlight_updates.send(()).ok();
1124        }
1125
1126        true
1127    }
1128
1129    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1130        let Some(assist) = self.assists.get(&assist_id) else {
1131            return;
1132        };
1133
1134        let assist_group = &self.assist_groups[&assist.group_id];
1135        let assist_ix = assist_group
1136            .assist_ids
1137            .iter()
1138            .position(|id| *id == assist_id)
1139            .unwrap();
1140        let assist_ids = assist_group
1141            .assist_ids
1142            .iter()
1143            .skip(assist_ix + 1)
1144            .chain(assist_group.assist_ids.iter().take(assist_ix));
1145
1146        for assist_id in assist_ids {
1147            let assist = &self.assists[assist_id];
1148            if assist.decorations.is_some() {
1149                self.focus_assist(*assist_id, window, cx);
1150                return;
1151            }
1152        }
1153
1154        assist
1155            .editor
1156            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1157            .ok();
1158    }
1159
1160    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1161        let Some(assist) = self.assists.get(&assist_id) else {
1162            return;
1163        };
1164
1165        if let Some(decorations) = assist.decorations.as_ref() {
1166            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1167                prompt_editor.editor.update(cx, |editor, cx| {
1168                    window.focus(&editor.focus_handle(cx));
1169                    editor.select_all(&SelectAll, window, cx);
1170                })
1171            });
1172        }
1173
1174        self.scroll_to_assist(assist_id, window, cx);
1175    }
1176
1177    pub fn scroll_to_assist(
1178        &mut self,
1179        assist_id: InlineAssistId,
1180        window: &mut Window,
1181        cx: &mut App,
1182    ) {
1183        let Some(assist) = self.assists.get(&assist_id) else {
1184            return;
1185        };
1186        let Some(editor) = assist.editor.upgrade() else {
1187            return;
1188        };
1189
1190        let position = assist.range.start;
1191        editor.update(cx, |editor, cx| {
1192            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1193                selections.select_anchor_ranges([position..position])
1194            });
1195
1196            let mut scroll_target_range = None;
1197            if let Some(decorations) = assist.decorations.as_ref() {
1198                scroll_target_range = maybe!({
1199                    let top = editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f64;
1200                    let bottom = editor.row_for_block(decorations.end_block_id, cx)?.0 as f64;
1201                    Some((top, bottom))
1202                });
1203                if scroll_target_range.is_none() {
1204                    log::error!("bug: failed to find blocks for scrolling to inline assist");
1205                }
1206            }
1207            let scroll_target_range = scroll_target_range.unwrap_or_else(|| {
1208                let snapshot = editor.snapshot(window, cx);
1209                let start_row = assist
1210                    .range
1211                    .start
1212                    .to_display_point(&snapshot.display_snapshot)
1213                    .row();
1214                let top = start_row.0 as ScrollOffset;
1215                let bottom = top + 1.0;
1216                (top, bottom)
1217            });
1218            let mut scroll_target_top = scroll_target_range.0;
1219            let mut scroll_target_bottom = scroll_target_range.1;
1220
1221            scroll_target_top -= editor.vertical_scroll_margin() as ScrollOffset;
1222            scroll_target_bottom += editor.vertical_scroll_margin() as ScrollOffset;
1223
1224            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1225            let scroll_top = editor.scroll_position(cx).y;
1226            let scroll_bottom = scroll_top + height_in_lines;
1227
1228            if scroll_target_top < scroll_top {
1229                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1230            } else if scroll_target_bottom > scroll_bottom {
1231                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1232                    editor.set_scroll_position(
1233                        point(0., scroll_target_bottom - height_in_lines),
1234                        window,
1235                        cx,
1236                    );
1237                } else {
1238                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1239                }
1240            }
1241        });
1242    }
1243
1244    fn unlink_assist_group(
1245        &mut self,
1246        assist_group_id: InlineAssistGroupId,
1247        window: &mut Window,
1248        cx: &mut App,
1249    ) -> Vec<InlineAssistId> {
1250        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1251        assist_group.linked = false;
1252
1253        for assist_id in &assist_group.assist_ids {
1254            let assist = self.assists.get_mut(assist_id).unwrap();
1255            if let Some(editor_decorations) = assist.decorations.as_ref() {
1256                editor_decorations
1257                    .prompt_editor
1258                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1259            }
1260        }
1261        assist_group.assist_ids.clone()
1262    }
1263
1264    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1265        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1266            assist
1267        } else {
1268            return;
1269        };
1270
1271        let assist_group_id = assist.group_id;
1272        if self.assist_groups[&assist_group_id].linked {
1273            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1274                self.start_assist(assist_id, window, cx);
1275            }
1276            return;
1277        }
1278
1279        let Some((user_prompt, mention_set)) = assist.user_prompt(cx).zip(assist.mention_set(cx))
1280        else {
1281            return;
1282        };
1283
1284        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1285        self.prompt_history.push_back(user_prompt.clone());
1286        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1287            self.prompt_history.pop_front();
1288        }
1289
1290        let Some(ConfiguredModel { model, .. }) =
1291            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1292        else {
1293            return;
1294        };
1295
1296        let context_task = load_context(&mention_set, cx).shared();
1297        assist
1298            .codegen
1299            .update(cx, |codegen, cx| {
1300                codegen.start(model, user_prompt, context_task, cx)
1301            })
1302            .log_err();
1303    }
1304
1305    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1306        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1307            assist
1308        } else {
1309            return;
1310        };
1311
1312        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1313    }
1314
1315    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1316        let mut gutter_pending_ranges = Vec::new();
1317        let mut gutter_transformed_ranges = Vec::new();
1318        let mut foreground_ranges = Vec::new();
1319        let mut inserted_row_ranges = Vec::new();
1320        let empty_assist_ids = Vec::new();
1321        let assist_ids = self
1322            .assists_by_editor
1323            .get(&editor.downgrade())
1324            .map_or(&empty_assist_ids, |editor_assists| {
1325                &editor_assists.assist_ids
1326            });
1327
1328        for assist_id in assist_ids {
1329            if let Some(assist) = self.assists.get(assist_id) {
1330                let codegen = assist.codegen.read(cx);
1331                let buffer = codegen.buffer(cx).read(cx).read(cx);
1332                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1333
1334                let pending_range =
1335                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1336                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1337                    gutter_pending_ranges.push(pending_range);
1338                }
1339
1340                if let Some(edit_position) = codegen.edit_position(cx) {
1341                    let edited_range = assist.range.start..edit_position;
1342                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1343                        gutter_transformed_ranges.push(edited_range);
1344                    }
1345                }
1346
1347                if assist.decorations.is_some() {
1348                    inserted_row_ranges
1349                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1350                }
1351            }
1352        }
1353
1354        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1355        merge_ranges(&mut foreground_ranges, &snapshot);
1356        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1357        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1358        editor.update(cx, |editor, cx| {
1359            enum GutterPendingRange {}
1360            if gutter_pending_ranges.is_empty() {
1361                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1362            } else {
1363                editor.highlight_gutter::<GutterPendingRange>(
1364                    gutter_pending_ranges,
1365                    |cx| cx.theme().status().info_background,
1366                    cx,
1367                )
1368            }
1369
1370            enum GutterTransformedRange {}
1371            if gutter_transformed_ranges.is_empty() {
1372                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1373            } else {
1374                editor.highlight_gutter::<GutterTransformedRange>(
1375                    gutter_transformed_ranges,
1376                    |cx| cx.theme().status().info,
1377                    cx,
1378                )
1379            }
1380
1381            if foreground_ranges.is_empty() {
1382                editor.clear_highlights::<InlineAssist>(cx);
1383            } else {
1384                editor.highlight_text::<InlineAssist>(
1385                    foreground_ranges,
1386                    HighlightStyle {
1387                        fade_out: Some(0.6),
1388                        ..Default::default()
1389                    },
1390                    cx,
1391                );
1392            }
1393
1394            editor.clear_row_highlights::<InlineAssist>();
1395            for row_range in inserted_row_ranges {
1396                editor.highlight_rows::<InlineAssist>(
1397                    row_range,
1398                    cx.theme().status().info_background,
1399                    Default::default(),
1400                    cx,
1401                );
1402            }
1403        });
1404    }
1405
1406    fn update_editor_blocks(
1407        &mut self,
1408        editor: &Entity<Editor>,
1409        assist_id: InlineAssistId,
1410        window: &mut Window,
1411        cx: &mut App,
1412    ) {
1413        let Some(assist) = self.assists.get_mut(&assist_id) else {
1414            return;
1415        };
1416        let Some(decorations) = assist.decorations.as_mut() else {
1417            return;
1418        };
1419
1420        let codegen = assist.codegen.read(cx);
1421        let old_snapshot = codegen.snapshot(cx);
1422        let old_buffer = codegen.old_buffer(cx);
1423        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1424
1425        editor.update(cx, |editor, cx| {
1426            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1427            editor.remove_blocks(old_blocks, None, cx);
1428
1429            let mut new_blocks = Vec::new();
1430            for (new_row, old_row_range) in deleted_row_ranges {
1431                let (_, buffer_start) = old_snapshot
1432                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1433                    .unwrap();
1434                let (_, buffer_end) = old_snapshot
1435                    .point_to_buffer_offset(Point::new(
1436                        *old_row_range.end(),
1437                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1438                    ))
1439                    .unwrap();
1440
1441                let deleted_lines_editor = cx.new(|cx| {
1442                    let multi_buffer =
1443                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1444                    multi_buffer.update(cx, |multi_buffer, cx| {
1445                        multi_buffer.push_excerpts(
1446                            old_buffer.clone(),
1447                            // todo(lw): buffer_start and buffer_end might come from different snapshots!
1448                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1449                            cx,
1450                        );
1451                    });
1452
1453                    enum DeletedLines {}
1454                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1455                    editor.disable_scrollbars_and_minimap(window, cx);
1456                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1457                    editor.set_show_wrap_guides(false, cx);
1458                    editor.set_show_gutter(false, cx);
1459                    editor.set_offset_content(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}