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