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