inline_assistant.rs

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