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.scroll_manager.set_forbid_vertical_scroll(true);
1460                    editor.set_read_only(true);
1461                    editor.set_show_edit_predictions(Some(false), window, cx);
1462                    editor.highlight_rows::<DeletedLines>(
1463                        Anchor::min()..Anchor::max(),
1464                        cx.theme().status().deleted_background,
1465                        Default::default(),
1466                        cx,
1467                    );
1468                    editor
1469                });
1470
1471                let height =
1472                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1473                new_blocks.push(BlockProperties {
1474                    placement: BlockPlacement::Above(new_row),
1475                    height: Some(height),
1476                    style: BlockStyle::Flex,
1477                    render: Arc::new(move |cx| {
1478                        div()
1479                            .block_mouse_except_scroll()
1480                            .bg(cx.theme().status().deleted_background)
1481                            .size_full()
1482                            .h(height as f32 * cx.window.line_height())
1483                            .pl(cx.margins.gutter.full_width())
1484                            .child(deleted_lines_editor.clone())
1485                            .into_any_element()
1486                    }),
1487                    priority: 0,
1488                });
1489            }
1490
1491            decorations.removed_line_block_ids = editor
1492                .insert_blocks(new_blocks, None, cx)
1493                .into_iter()
1494                .collect();
1495        })
1496    }
1497
1498    fn resolve_inline_assist_target(
1499        workspace: &mut Workspace,
1500        agent_panel: Option<Entity<AgentPanel>>,
1501        window: &mut Window,
1502        cx: &mut App,
1503    ) -> Option<InlineAssistTarget> {
1504        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx)
1505            && terminal_panel
1506                .read(cx)
1507                .focus_handle(cx)
1508                .contains_focused(window, cx)
1509            && let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1510                pane.read(cx)
1511                    .active_item()
1512                    .and_then(|t| t.downcast::<TerminalView>())
1513            })
1514        {
1515            return Some(InlineAssistTarget::Terminal(terminal_view));
1516        }
1517
1518        let text_thread_editor = agent_panel
1519            .and_then(|panel| panel.read(cx).active_text_thread_editor())
1520            .and_then(|editor| {
1521                let editor = &editor.read(cx).editor().clone();
1522                if editor.read(cx).is_focused(window) {
1523                    Some(editor.clone())
1524                } else {
1525                    None
1526                }
1527            });
1528
1529        if let Some(text_thread_editor) = text_thread_editor {
1530            Some(InlineAssistTarget::Editor(text_thread_editor))
1531        } else if let Some(workspace_editor) = workspace
1532            .active_item(cx)
1533            .and_then(|item| item.act_as::<Editor>(cx))
1534        {
1535            Some(InlineAssistTarget::Editor(workspace_editor))
1536        } else {
1537            workspace
1538                .active_item(cx)
1539                .and_then(|item| item.act_as::<TerminalView>(cx))
1540                .map(InlineAssistTarget::Terminal)
1541        }
1542    }
1543}
1544
1545struct EditorInlineAssists {
1546    assist_ids: Vec<InlineAssistId>,
1547    scroll_lock: Option<InlineAssistScrollLock>,
1548    highlight_updates: watch::Sender<()>,
1549    _update_highlights: Task<Result<()>>,
1550    _subscriptions: Vec<gpui::Subscription>,
1551}
1552
1553struct InlineAssistScrollLock {
1554    assist_id: InlineAssistId,
1555    distance_from_top: ScrollOffset,
1556}
1557
1558impl EditorInlineAssists {
1559    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1560        let (highlight_updates_tx, mut highlight_updates_rx) = watch::channel(());
1561        Self {
1562            assist_ids: Vec::new(),
1563            scroll_lock: None,
1564            highlight_updates: highlight_updates_tx,
1565            _update_highlights: cx.spawn({
1566                let editor = editor.downgrade();
1567                async move |cx| {
1568                    while let Ok(()) = highlight_updates_rx.changed().await {
1569                        let editor = editor.upgrade().context("editor was dropped")?;
1570                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1571                            assistant.update_editor_highlights(&editor, cx);
1572                        })?;
1573                    }
1574                    Ok(())
1575                }
1576            }),
1577            _subscriptions: vec![
1578                cx.observe_release_in(editor, window, {
1579                    let editor = editor.downgrade();
1580                    |_, window, cx| {
1581                        InlineAssistant::update_global(cx, |this, cx| {
1582                            this.handle_editor_release(editor, window, cx);
1583                        })
1584                    }
1585                }),
1586                window.observe(editor, cx, move |editor, window, cx| {
1587                    InlineAssistant::update_global(cx, |this, cx| {
1588                        this.handle_editor_change(editor, window, cx)
1589                    })
1590                }),
1591                window.subscribe(editor, cx, move |editor, event, window, cx| {
1592                    InlineAssistant::update_global(cx, |this, cx| {
1593                        this.handle_editor_event(editor, event, window, cx)
1594                    })
1595                }),
1596                editor.update(cx, |editor, cx| {
1597                    let editor_handle = cx.entity().downgrade();
1598                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1599                        InlineAssistant::update_global(cx, |this, cx| {
1600                            if let Some(editor) = editor_handle.upgrade() {
1601                                this.handle_editor_newline(editor, window, cx)
1602                            }
1603                        })
1604                    })
1605                }),
1606                editor.update(cx, |editor, cx| {
1607                    let editor_handle = cx.entity().downgrade();
1608                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1609                        InlineAssistant::update_global(cx, |this, cx| {
1610                            if let Some(editor) = editor_handle.upgrade() {
1611                                this.handle_editor_cancel(editor, window, cx)
1612                            }
1613                        })
1614                    })
1615                }),
1616            ],
1617        }
1618    }
1619}
1620
1621struct InlineAssistGroup {
1622    assist_ids: Vec<InlineAssistId>,
1623    linked: bool,
1624    active_assist_id: Option<InlineAssistId>,
1625}
1626
1627impl InlineAssistGroup {
1628    fn new() -> Self {
1629        Self {
1630            assist_ids: Vec::new(),
1631            linked: true,
1632            active_assist_id: None,
1633        }
1634    }
1635}
1636
1637fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1638    let editor = editor.clone();
1639
1640    Arc::new(move |cx: &mut BlockContext| {
1641        let editor_margins = editor.read(cx).editor_margins();
1642
1643        *editor_margins.lock() = *cx.margins;
1644        editor.clone().into_any_element()
1645    })
1646}
1647
1648#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1649struct InlineAssistGroupId(usize);
1650
1651impl InlineAssistGroupId {
1652    fn post_inc(&mut self) -> InlineAssistGroupId {
1653        let id = *self;
1654        self.0 += 1;
1655        id
1656    }
1657}
1658
1659pub struct InlineAssist {
1660    group_id: InlineAssistGroupId,
1661    range: Range<Anchor>,
1662    editor: WeakEntity<Editor>,
1663    decorations: Option<InlineAssistDecorations>,
1664    codegen: Entity<BufferCodegen>,
1665    _subscriptions: Vec<Subscription>,
1666    workspace: WeakEntity<Workspace>,
1667}
1668
1669impl InlineAssist {
1670    fn new(
1671        assist_id: InlineAssistId,
1672        group_id: InlineAssistGroupId,
1673        editor: &Entity<Editor>,
1674        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1675        prompt_block_id: CustomBlockId,
1676        end_block_id: CustomBlockId,
1677        range: Range<Anchor>,
1678        codegen: Entity<BufferCodegen>,
1679        workspace: WeakEntity<Workspace>,
1680        window: &mut Window,
1681        cx: &mut App,
1682    ) -> Self {
1683        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1684        InlineAssist {
1685            group_id,
1686            editor: editor.downgrade(),
1687            decorations: Some(InlineAssistDecorations {
1688                prompt_block_id,
1689                prompt_editor: prompt_editor.clone(),
1690                removed_line_block_ids: HashSet::default(),
1691                end_block_id,
1692            }),
1693            range,
1694            codegen: codegen.clone(),
1695            workspace,
1696            _subscriptions: vec![
1697                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1698                    InlineAssistant::update_global(cx, |this, cx| {
1699                        this.handle_prompt_editor_focus_in(assist_id, cx)
1700                    })
1701                }),
1702                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1703                    InlineAssistant::update_global(cx, |this, cx| {
1704                        this.handle_prompt_editor_focus_out(assist_id, cx)
1705                    })
1706                }),
1707                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1708                    InlineAssistant::update_global(cx, |this, cx| {
1709                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1710                    })
1711                }),
1712                window.observe(&codegen, cx, {
1713                    let editor = editor.downgrade();
1714                    move |_, window, cx| {
1715                        if let Some(editor) = editor.upgrade() {
1716                            InlineAssistant::update_global(cx, |this, cx| {
1717                                if let Some(editor_assists) =
1718                                    this.assists_by_editor.get_mut(&editor.downgrade())
1719                                {
1720                                    editor_assists.highlight_updates.send(()).ok();
1721                                }
1722
1723                                this.update_editor_blocks(&editor, assist_id, window, cx);
1724                            })
1725                        }
1726                    }
1727                }),
1728                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1729                    InlineAssistant::update_global(cx, |this, cx| match event {
1730                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1731                        CodegenEvent::Finished => {
1732                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1733                                assist
1734                            } else {
1735                                return;
1736                            };
1737
1738                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx)
1739                                && assist.decorations.is_none()
1740                                && let Some(workspace) = assist.workspace.upgrade()
1741                            {
1742                                let error = format!("Inline assistant error: {}", error);
1743                                workspace.update(cx, |workspace, cx| {
1744                                    struct InlineAssistantError;
1745
1746                                    let id = NotificationId::composite::<InlineAssistantError>(
1747                                        assist_id.0,
1748                                    );
1749
1750                                    workspace.show_toast(Toast::new(id, error), cx);
1751                                })
1752                            }
1753
1754                            if assist.decorations.is_none() {
1755                                this.finish_assist(assist_id, false, window, cx);
1756                            }
1757                        }
1758                    })
1759                }),
1760            ],
1761        }
1762    }
1763
1764    fn user_prompt(&self, cx: &App) -> Option<String> {
1765        let decorations = self.decorations.as_ref()?;
1766        Some(decorations.prompt_editor.read(cx).prompt(cx))
1767    }
1768
1769    fn mention_set(&self, cx: &App) -> Option<Entity<MentionSet>> {
1770        let decorations = self.decorations.as_ref()?;
1771        Some(decorations.prompt_editor.read(cx).mention_set().clone())
1772    }
1773}
1774
1775struct InlineAssistDecorations {
1776    prompt_block_id: CustomBlockId,
1777    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1778    removed_line_block_ids: HashSet<CustomBlockId>,
1779    end_block_id: CustomBlockId,
1780}
1781
1782struct AssistantCodeActionProvider {
1783    editor: WeakEntity<Editor>,
1784    workspace: WeakEntity<Workspace>,
1785}
1786
1787const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant";
1788
1789impl CodeActionProvider for AssistantCodeActionProvider {
1790    fn id(&self) -> Arc<str> {
1791        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1792    }
1793
1794    fn code_actions(
1795        &self,
1796        buffer: &Entity<Buffer>,
1797        range: Range<text::Anchor>,
1798        _: &mut Window,
1799        cx: &mut App,
1800    ) -> Task<Result<Vec<CodeAction>>> {
1801        if !AgentSettings::get_global(cx).enabled(cx) {
1802            return Task::ready(Ok(Vec::new()));
1803        }
1804
1805        let snapshot = buffer.read(cx).snapshot();
1806        let mut range = range.to_point(&snapshot);
1807
1808        // Expand the range to line boundaries.
1809        range.start.column = 0;
1810        range.end.column = snapshot.line_len(range.end.row);
1811
1812        let mut has_diagnostics = false;
1813        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1814            range.start = cmp::min(range.start, diagnostic.range.start);
1815            range.end = cmp::max(range.end, diagnostic.range.end);
1816            has_diagnostics = true;
1817        }
1818        if has_diagnostics {
1819            let symbols_containing_start = snapshot.symbols_containing(range.start, None);
1820            if let Some(symbol) = symbols_containing_start.last() {
1821                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1822                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1823            }
1824            let symbols_containing_end = snapshot.symbols_containing(range.end, None);
1825            if let Some(symbol) = symbols_containing_end.last() {
1826                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1827                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1828            }
1829
1830            Task::ready(Ok(vec![CodeAction {
1831                server_id: language::LanguageServerId(0),
1832                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1833                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1834                    title: "Fix with Assistant".into(),
1835                    ..Default::default()
1836                })),
1837                resolved: true,
1838            }]))
1839        } else {
1840            Task::ready(Ok(Vec::new()))
1841        }
1842    }
1843
1844    fn apply_code_action(
1845        &self,
1846        buffer: Entity<Buffer>,
1847        action: CodeAction,
1848        excerpt_id: ExcerptId,
1849        _push_to_history: bool,
1850        window: &mut Window,
1851        cx: &mut App,
1852    ) -> Task<Result<ProjectTransaction>> {
1853        let editor = self.editor.clone();
1854        let workspace = self.workspace.clone();
1855        let prompt_store = PromptStore::global(cx);
1856        window.spawn(cx, async move |cx| {
1857            let workspace = workspace.upgrade().context("workspace was released")?;
1858            let thread_store = cx.update(|_window, cx| {
1859                anyhow::Ok(
1860                    workspace
1861                        .read(cx)
1862                        .panel::<AgentPanel>(cx)
1863                        .context("missing agent panel")?
1864                        .read(cx)
1865                        .thread_store()
1866                        .clone(),
1867                )
1868            })??;
1869            let editor = editor.upgrade().context("editor was released")?;
1870            let range = editor
1871                .update(cx, |editor, cx| {
1872                    editor.buffer().update(cx, |multibuffer, cx| {
1873                        let buffer = buffer.read(cx);
1874                        let multibuffer_snapshot = multibuffer.read(cx);
1875
1876                        let old_context_range =
1877                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1878                        let mut new_context_range = old_context_range.clone();
1879                        if action
1880                            .range
1881                            .start
1882                            .cmp(&old_context_range.start, buffer)
1883                            .is_lt()
1884                        {
1885                            new_context_range.start = action.range.start;
1886                        }
1887                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1888                            new_context_range.end = action.range.end;
1889                        }
1890                        drop(multibuffer_snapshot);
1891
1892                        if new_context_range != old_context_range {
1893                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1894                        }
1895
1896                        let multibuffer_snapshot = multibuffer.read(cx);
1897                        multibuffer_snapshot.anchor_range_in_excerpt(excerpt_id, action.range)
1898                    })
1899                })?
1900                .context("invalid range")?;
1901
1902            let prompt_store = prompt_store.await.ok();
1903            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1904                let assist_id = assistant.suggest_assist(
1905                    &editor,
1906                    range,
1907                    "Fix Diagnostics".into(),
1908                    None,
1909                    true,
1910                    workspace,
1911                    thread_store,
1912                    prompt_store,
1913                    window,
1914                    cx,
1915                );
1916                assistant.start_assist(assist_id, window, cx);
1917            })?;
1918
1919            Ok(ProjectTransaction::default())
1920        })
1921    }
1922}
1923
1924fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1925    ranges.sort_unstable_by(|a, b| {
1926        a.start
1927            .cmp(&b.start, buffer)
1928            .then_with(|| b.end.cmp(&a.end, buffer))
1929    });
1930
1931    let mut ix = 0;
1932    while ix + 1 < ranges.len() {
1933        let b = ranges[ix + 1].clone();
1934        let a = &mut ranges[ix];
1935        if a.end.cmp(&b.start, buffer).is_gt() {
1936            if a.end.cmp(&b.end, buffer).is_lt() {
1937                a.end = b.end;
1938            }
1939            ranges.remove(ix + 1);
1940        } else {
1941            ix += 1;
1942        }
1943    }
1944}