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(cx);
 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                {
 188                    for assist_id in editor_assists.assist_ids.clone() {
 189                        let assist = &self.assists[&assist_id];
 190                        if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
 191                            self.finish_assist(assist_id, false, window, cx)
 192                        }
 193                    }
 194                }
 195            }
 196            workspace::Event::ItemAdded { item } => {
 197                self.register_workspace_item(&workspace, item.as_ref(), window, cx);
 198            }
 199            _ => (),
 200        }
 201    }
 202
 203    fn register_workspace_item(
 204        &mut self,
 205        workspace: &Entity<Workspace>,
 206        item: &dyn ItemHandle,
 207        window: &mut Window,
 208        cx: &mut App,
 209    ) {
 210        let is_assistant2_enabled = !DisableAiSettings::get_global(cx).disable_ai;
 211
 212        if let Some(editor) = item.act_as::<Editor>(cx) {
 213            editor.update(cx, |editor, cx| {
 214                if is_assistant2_enabled {
 215                    let panel = workspace.read(cx).panel::<AgentPanel>(cx);
 216                    let thread_store = panel
 217                        .as_ref()
 218                        .map(|agent_panel| agent_panel.read(cx).thread_store().downgrade());
 219                    let text_thread_store = panel
 220                        .map(|agent_panel| agent_panel.read(cx).text_thread_store().downgrade());
 221
 222                    editor.add_code_action_provider(
 223                        Rc::new(AssistantCodeActionProvider {
 224                            editor: cx.entity().downgrade(),
 225                            workspace: workspace.downgrade(),
 226                            thread_store,
 227                            text_thread_store,
 228                        }),
 229                        window,
 230                        cx,
 231                    );
 232
 233                    if DisableAiSettings::get_global(cx).disable_ai {
 234                        // Cancel any active edit predictions
 235                        if editor.has_active_edit_prediction() {
 236                            editor.cancel(&Default::default(), window, cx);
 237                        }
 238                    }
 239
 240                    // Remove the Assistant1 code action provider, as it still might be registered.
 241                    editor.remove_code_action_provider("assistant".into(), window, cx);
 242                } else {
 243                    editor.remove_code_action_provider(
 244                        ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
 245                        window,
 246                        cx,
 247                    );
 248                }
 249            });
 250        }
 251    }
 252
 253    pub fn inline_assist(
 254        workspace: &mut Workspace,
 255        action: &zed_actions::assistant::InlineAssist,
 256        window: &mut Window,
 257        cx: &mut Context<Workspace>,
 258    ) {
 259        if !AgentSettings::get_global(cx).enabled(cx) {
 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                    {
 347                        cx.update(|window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
 348                            .ok();
 349                    }
 350                    anyhow::Ok(())
 351                })
 352                .detach_and_log_err(cx);
 353            }
 354        } else {
 355            handle_assist(window, cx);
 356        }
 357    }
 358
 359    pub fn assist(
 360        &mut self,
 361        editor: &Entity<Editor>,
 362        workspace: WeakEntity<Workspace>,
 363        context_store: Entity<ContextStore>,
 364        project: WeakEntity<Project>,
 365        prompt_store: Option<Entity<PromptStore>>,
 366        thread_store: Option<WeakEntity<ThreadStore>>,
 367        text_thread_store: Option<WeakEntity<TextThreadStore>>,
 368        initial_prompt: Option<String>,
 369        window: &mut Window,
 370        cx: &mut App,
 371    ) {
 372        let (snapshot, initial_selections, newest_selection) = editor.update(cx, |editor, cx| {
 373            let selections = editor.selections.all::<Point>(cx);
 374            let newest_selection = editor.selections.newest::<Point>(cx);
 375            (editor.snapshot(window, cx), selections, newest_selection)
 376        });
 377
 378        // Check if there is already an inline assistant that contains the
 379        // newest selection, if there is, focus it
 380        if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 381            for assist_id in &editor_assists.assist_ids {
 382                let assist = &self.assists[assist_id];
 383                let range = assist.range.to_point(&snapshot.buffer_snapshot);
 384                if range.start.row <= newest_selection.start.row
 385                    && newest_selection.end.row <= range.end.row
 386                {
 387                    self.focus_assist(*assist_id, window, cx);
 388                    return;
 389                }
 390            }
 391        }
 392
 393        let mut selections = Vec::<Selection<Point>>::new();
 394        let mut newest_selection = None;
 395        for mut selection in initial_selections {
 396            if selection.end > selection.start {
 397                selection.start.column = 0;
 398                // If the selection ends at the start of the line, we don't want to include it.
 399                if selection.end.column == 0 {
 400                    selection.end.row -= 1;
 401                }
 402                selection.end.column = snapshot
 403                    .buffer_snapshot
 404                    .line_len(MultiBufferRow(selection.end.row));
 405            } else if let Some(fold) =
 406                snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
 407            {
 408                selection.start = fold.range().start;
 409                selection.end = fold.range().end;
 410                if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot.max_row() {
 411                    let chars = snapshot
 412                        .buffer_snapshot
 413                        .chars_at(Point::new(selection.end.row + 1, 0));
 414
 415                    for c in chars {
 416                        if c == '\n' {
 417                            break;
 418                        }
 419                        if c.is_whitespace() {
 420                            continue;
 421                        }
 422                        if snapshot
 423                            .language_at(selection.end)
 424                            .is_some_and(|language| language.config().brackets.is_closing_brace(c))
 425                        {
 426                            selection.end.row += 1;
 427                            selection.end.column = snapshot
 428                                .buffer_snapshot
 429                                .line_len(MultiBufferRow(selection.end.row));
 430                        }
 431                    }
 432                }
 433            }
 434
 435            if let Some(prev_selection) = selections.last_mut()
 436                && selection.start <= prev_selection.end
 437            {
 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                editor_assists.scroll_lock = editor
 746                    .row_for_block(decorations.prompt_block_id, cx)
 747                    .map(|row| row.0 as f32)
 748                    .filter(|prompt_row| (scroll_top..scroll_bottom).contains(&prompt_row))
 749                    .map(|prompt_row| InlineAssistScrollLock {
 750                        assist_id,
 751                        distance_from_top: prompt_row - scroll_top,
 752                    });
 753            })
 754            .ok();
 755    }
 756
 757    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 758        let assist = &self.assists[&assist_id];
 759        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 760        if assist_group.active_assist_id == Some(assist_id) {
 761            assist_group.active_assist_id = None;
 762            if assist_group.linked {
 763                for assist_id in &assist_group.assist_ids {
 764                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 765                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 766                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 767                        });
 768                    }
 769                }
 770            }
 771        }
 772    }
 773
 774    fn handle_prompt_editor_event(
 775        &mut self,
 776        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 777        event: &PromptEditorEvent,
 778        window: &mut Window,
 779        cx: &mut App,
 780    ) {
 781        let assist_id = prompt_editor.read(cx).id();
 782        match event {
 783            PromptEditorEvent::StartRequested => {
 784                self.start_assist(assist_id, window, cx);
 785            }
 786            PromptEditorEvent::StopRequested => {
 787                self.stop_assist(assist_id, cx);
 788            }
 789            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 790                self.finish_assist(assist_id, false, window, cx);
 791            }
 792            PromptEditorEvent::CancelRequested => {
 793                self.finish_assist(assist_id, true, window, cx);
 794            }
 795            PromptEditorEvent::Resized { .. } => {
 796                // This only matters for the terminal inline assistant
 797            }
 798        }
 799    }
 800
 801    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 802        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 803            return;
 804        };
 805
 806        if editor.read(cx).selections.count() == 1 {
 807            let (selection, buffer) = editor.update(cx, |editor, cx| {
 808                (
 809                    editor.selections.newest::<usize>(cx),
 810                    editor.buffer().read(cx).snapshot(cx),
 811                )
 812            });
 813            for assist_id in &editor_assists.assist_ids {
 814                let assist = &self.assists[assist_id];
 815                let assist_range = assist.range.to_offset(&buffer);
 816                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 817                {
 818                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 819                        self.dismiss_assist(*assist_id, window, cx);
 820                    } else {
 821                        self.finish_assist(*assist_id, false, window, cx);
 822                    }
 823
 824                    return;
 825                }
 826            }
 827        }
 828
 829        cx.propagate();
 830    }
 831
 832    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 833        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 834            return;
 835        };
 836
 837        if editor.read(cx).selections.count() == 1 {
 838            let (selection, buffer) = editor.update(cx, |editor, cx| {
 839                (
 840                    editor.selections.newest::<usize>(cx),
 841                    editor.buffer().read(cx).snapshot(cx),
 842                )
 843            });
 844            let mut closest_assist_fallback = None;
 845            for assist_id in &editor_assists.assist_ids {
 846                let assist = &self.assists[assist_id];
 847                let assist_range = assist.range.to_offset(&buffer);
 848                if assist.decorations.is_some() {
 849                    if assist_range.contains(&selection.start)
 850                        && assist_range.contains(&selection.end)
 851                    {
 852                        self.focus_assist(*assist_id, window, cx);
 853                        return;
 854                    } else {
 855                        let distance_from_selection = assist_range
 856                            .start
 857                            .abs_diff(selection.start)
 858                            .min(assist_range.start.abs_diff(selection.end))
 859                            + assist_range
 860                                .end
 861                                .abs_diff(selection.start)
 862                                .min(assist_range.end.abs_diff(selection.end));
 863                        match closest_assist_fallback {
 864                            Some((_, old_distance)) => {
 865                                if distance_from_selection < old_distance {
 866                                    closest_assist_fallback =
 867                                        Some((assist_id, distance_from_selection));
 868                                }
 869                            }
 870                            None => {
 871                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 872                            }
 873                        }
 874                    }
 875                }
 876            }
 877
 878            if let Some((&assist_id, _)) = closest_assist_fallback {
 879                self.focus_assist(assist_id, window, cx);
 880            }
 881        }
 882
 883        cx.propagate();
 884    }
 885
 886    fn handle_editor_release(
 887        &mut self,
 888        editor: WeakEntity<Editor>,
 889        window: &mut Window,
 890        cx: &mut App,
 891    ) {
 892        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 893            for assist_id in editor_assists.assist_ids.clone() {
 894                self.finish_assist(assist_id, true, window, cx);
 895            }
 896        }
 897    }
 898
 899    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 900        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 901            return;
 902        };
 903        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 904            return;
 905        };
 906        let assist = &self.assists[&scroll_lock.assist_id];
 907        let Some(decorations) = assist.decorations.as_ref() else {
 908            return;
 909        };
 910
 911        editor.update(cx, |editor, cx| {
 912            let scroll_position = editor.scroll_position(cx);
 913            let target_scroll_top = editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f32
 914                - scroll_lock.distance_from_top;
 915            if target_scroll_top != scroll_position.y {
 916                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 917            }
 918            Some(())
 919        });
 920    }
 921
 922    fn handle_editor_event(
 923        &mut self,
 924        editor: Entity<Editor>,
 925        event: &EditorEvent,
 926        window: &mut Window,
 927        cx: &mut App,
 928    ) {
 929        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 930            return;
 931        };
 932
 933        match event {
 934            EditorEvent::Edited { transaction_id } => {
 935                let buffer = editor.read(cx).buffer().read(cx);
 936                let edited_ranges =
 937                    buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
 938                let snapshot = buffer.snapshot(cx);
 939
 940                for assist_id in editor_assists.assist_ids.clone() {
 941                    let assist = &self.assists[&assist_id];
 942                    if matches!(
 943                        assist.codegen.read(cx).status(cx),
 944                        CodegenStatus::Error(_) | CodegenStatus::Done
 945                    ) {
 946                        let assist_range = assist.range.to_offset(&snapshot);
 947                        if edited_ranges
 948                            .iter()
 949                            .any(|range| range.overlaps(&assist_range))
 950                        {
 951                            self.finish_assist(assist_id, false, window, cx);
 952                        }
 953                    }
 954                }
 955            }
 956            EditorEvent::ScrollPositionChanged { .. } => {
 957                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 958                    let assist = &self.assists[&scroll_lock.assist_id];
 959                    if let Some(decorations) = assist.decorations.as_ref() {
 960                        let distance_from_top = editor.update(cx, |editor, cx| {
 961                            let scroll_top = editor.scroll_position(cx).y;
 962                            let prompt_row =
 963                                editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f32;
 964                            Some(prompt_row - scroll_top)
 965                        });
 966
 967                        if distance_from_top.is_none_or(|distance_from_top| {
 968                            distance_from_top != scroll_lock.distance_from_top
 969                        }) {
 970                            editor_assists.scroll_lock = None;
 971                        }
 972                    }
 973                }
 974            }
 975            EditorEvent::SelectionsChanged { .. } => {
 976                for assist_id in editor_assists.assist_ids.clone() {
 977                    let assist = &self.assists[&assist_id];
 978                    if let Some(decorations) = assist.decorations.as_ref()
 979                        && decorations
 980                            .prompt_editor
 981                            .focus_handle(cx)
 982                            .is_focused(window)
 983                    {
 984                        return;
 985                    }
 986                }
 987
 988                editor_assists.scroll_lock = None;
 989            }
 990            _ => {}
 991        }
 992    }
 993
 994    pub fn finish_assist(
 995        &mut self,
 996        assist_id: InlineAssistId,
 997        undo: bool,
 998        window: &mut Window,
 999        cx: &mut App,
1000    ) {
1001        if let Some(assist) = self.assists.get(&assist_id) {
1002            let assist_group_id = assist.group_id;
1003            if self.assist_groups[&assist_group_id].linked {
1004                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1005                    self.finish_assist(assist_id, undo, window, cx);
1006                }
1007                return;
1008            }
1009        }
1010
1011        self.dismiss_assist(assist_id, window, cx);
1012
1013        if let Some(assist) = self.assists.remove(&assist_id) {
1014            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
1015            {
1016                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1017                if entry.get().assist_ids.is_empty() {
1018                    entry.remove();
1019                }
1020            }
1021
1022            if let hash_map::Entry::Occupied(mut entry) =
1023                self.assists_by_editor.entry(assist.editor.clone())
1024            {
1025                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1026                if entry.get().assist_ids.is_empty() {
1027                    entry.remove();
1028                    if let Some(editor) = assist.editor.upgrade() {
1029                        self.update_editor_highlights(&editor, cx);
1030                    }
1031                } else {
1032                    entry.get_mut().highlight_updates.send(()).ok();
1033                }
1034            }
1035
1036            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1037            let message_id = active_alternative.read(cx).message_id.clone();
1038
1039            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1040                let language_name = assist.editor.upgrade().and_then(|editor| {
1041                    let multibuffer = editor.read(cx).buffer().read(cx);
1042                    let snapshot = multibuffer.snapshot(cx);
1043                    let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
1044                    ranges
1045                        .first()
1046                        .and_then(|(buffer, _, _)| buffer.language())
1047                        .map(|language| language.name())
1048                });
1049                report_assistant_event(
1050                    AssistantEventData {
1051                        conversation_id: None,
1052                        kind: AssistantKind::Inline,
1053                        message_id,
1054                        phase: if undo {
1055                            AssistantPhase::Rejected
1056                        } else {
1057                            AssistantPhase::Accepted
1058                        },
1059                        model: model.model.telemetry_id(),
1060                        model_provider: model.model.provider_id().to_string(),
1061                        response_latency: None,
1062                        error_message: None,
1063                        language_name: language_name.map(|name| name.to_proto()),
1064                    },
1065                    Some(self.telemetry.clone()),
1066                    cx.http_client(),
1067                    model.model.api_key(cx),
1068                    cx.background_executor(),
1069                );
1070            }
1071
1072            if undo {
1073                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1074            } else {
1075                self.confirmed_assists.insert(assist_id, active_alternative);
1076            }
1077        }
1078    }
1079
1080    fn dismiss_assist(
1081        &mut self,
1082        assist_id: InlineAssistId,
1083        window: &mut Window,
1084        cx: &mut App,
1085    ) -> bool {
1086        let Some(assist) = self.assists.get_mut(&assist_id) else {
1087            return false;
1088        };
1089        let Some(editor) = assist.editor.upgrade() else {
1090            return false;
1091        };
1092        let Some(decorations) = assist.decorations.take() else {
1093            return false;
1094        };
1095
1096        editor.update(cx, |editor, cx| {
1097            let mut to_remove = decorations.removed_line_block_ids;
1098            to_remove.insert(decorations.prompt_block_id);
1099            to_remove.insert(decorations.end_block_id);
1100            editor.remove_blocks(to_remove, None, cx);
1101        });
1102
1103        if decorations
1104            .prompt_editor
1105            .focus_handle(cx)
1106            .contains_focused(window, cx)
1107        {
1108            self.focus_next_assist(assist_id, window, cx);
1109        }
1110
1111        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1112            if editor_assists
1113                .scroll_lock
1114                .as_ref()
1115                .is_some_and(|lock| lock.assist_id == assist_id)
1116            {
1117                editor_assists.scroll_lock = None;
1118            }
1119            editor_assists.highlight_updates.send(()).ok();
1120        }
1121
1122        true
1123    }
1124
1125    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1126        let Some(assist) = self.assists.get(&assist_id) else {
1127            return;
1128        };
1129
1130        let assist_group = &self.assist_groups[&assist.group_id];
1131        let assist_ix = assist_group
1132            .assist_ids
1133            .iter()
1134            .position(|id| *id == assist_id)
1135            .unwrap();
1136        let assist_ids = assist_group
1137            .assist_ids
1138            .iter()
1139            .skip(assist_ix + 1)
1140            .chain(assist_group.assist_ids.iter().take(assist_ix));
1141
1142        for assist_id in assist_ids {
1143            let assist = &self.assists[assist_id];
1144            if assist.decorations.is_some() {
1145                self.focus_assist(*assist_id, window, cx);
1146                return;
1147            }
1148        }
1149
1150        assist
1151            .editor
1152            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1153            .ok();
1154    }
1155
1156    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1157        let Some(assist) = self.assists.get(&assist_id) else {
1158            return;
1159        };
1160
1161        if let Some(decorations) = assist.decorations.as_ref() {
1162            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1163                prompt_editor.editor.update(cx, |editor, cx| {
1164                    window.focus(&editor.focus_handle(cx));
1165                    editor.select_all(&SelectAll, window, cx);
1166                })
1167            });
1168        }
1169
1170        self.scroll_to_assist(assist_id, window, cx);
1171    }
1172
1173    pub fn scroll_to_assist(
1174        &mut self,
1175        assist_id: InlineAssistId,
1176        window: &mut Window,
1177        cx: &mut App,
1178    ) {
1179        let Some(assist) = self.assists.get(&assist_id) else {
1180            return;
1181        };
1182        let Some(editor) = assist.editor.upgrade() else {
1183            return;
1184        };
1185
1186        let position = assist.range.start;
1187        editor.update(cx, |editor, cx| {
1188            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1189                selections.select_anchor_ranges([position..position])
1190            });
1191
1192            let mut scroll_target_range = None;
1193            if let Some(decorations) = assist.decorations.as_ref() {
1194                scroll_target_range = maybe!({
1195                    let top = editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f32;
1196                    let bottom = editor.row_for_block(decorations.end_block_id, cx)?.0 as f32;
1197                    Some((top, bottom))
1198                });
1199                if scroll_target_range.is_none() {
1200                    log::error!("bug: failed to find blocks for scrolling to inline assist");
1201                }
1202            }
1203            let scroll_target_range = scroll_target_range.unwrap_or_else(|| {
1204                let snapshot = editor.snapshot(window, cx);
1205                let start_row = assist
1206                    .range
1207                    .start
1208                    .to_display_point(&snapshot.display_snapshot)
1209                    .row();
1210                let top = start_row.0 as f32;
1211                let bottom = top + 1.0;
1212                (top, bottom)
1213            });
1214            let mut scroll_target_top = scroll_target_range.0;
1215            let mut scroll_target_bottom = scroll_target_range.1;
1216
1217            scroll_target_top -= editor.vertical_scroll_margin() as f32;
1218            scroll_target_bottom += editor.vertical_scroll_margin() as f32;
1219
1220            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1221            let scroll_top = editor.scroll_position(cx).y;
1222            let scroll_bottom = scroll_top + height_in_lines;
1223
1224            if scroll_target_top < scroll_top {
1225                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1226            } else if scroll_target_bottom > scroll_bottom {
1227                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1228                    editor.set_scroll_position(
1229                        point(0., scroll_target_bottom - height_in_lines),
1230                        window,
1231                        cx,
1232                    );
1233                } else {
1234                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1235                }
1236            }
1237        });
1238    }
1239
1240    fn unlink_assist_group(
1241        &mut self,
1242        assist_group_id: InlineAssistGroupId,
1243        window: &mut Window,
1244        cx: &mut App,
1245    ) -> Vec<InlineAssistId> {
1246        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1247        assist_group.linked = false;
1248
1249        for assist_id in &assist_group.assist_ids {
1250            let assist = self.assists.get_mut(assist_id).unwrap();
1251            if let Some(editor_decorations) = assist.decorations.as_ref() {
1252                editor_decorations
1253                    .prompt_editor
1254                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1255            }
1256        }
1257        assist_group.assist_ids.clone()
1258    }
1259
1260    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1261        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1262            assist
1263        } else {
1264            return;
1265        };
1266
1267        let assist_group_id = assist.group_id;
1268        if self.assist_groups[&assist_group_id].linked {
1269            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1270                self.start_assist(assist_id, window, cx);
1271            }
1272            return;
1273        }
1274
1275        let Some(user_prompt) = assist.user_prompt(cx) else {
1276            return;
1277        };
1278
1279        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1280        self.prompt_history.push_back(user_prompt.clone());
1281        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1282            self.prompt_history.pop_front();
1283        }
1284
1285        let Some(ConfiguredModel { model, .. }) =
1286            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1287        else {
1288            return;
1289        };
1290
1291        assist
1292            .codegen
1293            .update(cx, |codegen, cx| codegen.start(model, user_prompt, cx))
1294            .log_err();
1295    }
1296
1297    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1298        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1299            assist
1300        } else {
1301            return;
1302        };
1303
1304        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1305    }
1306
1307    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1308        let mut gutter_pending_ranges = Vec::new();
1309        let mut gutter_transformed_ranges = Vec::new();
1310        let mut foreground_ranges = Vec::new();
1311        let mut inserted_row_ranges = Vec::new();
1312        let empty_assist_ids = Vec::new();
1313        let assist_ids = self
1314            .assists_by_editor
1315            .get(&editor.downgrade())
1316            .map_or(&empty_assist_ids, |editor_assists| {
1317                &editor_assists.assist_ids
1318            });
1319
1320        for assist_id in assist_ids {
1321            if let Some(assist) = self.assists.get(assist_id) {
1322                let codegen = assist.codegen.read(cx);
1323                let buffer = codegen.buffer(cx).read(cx).read(cx);
1324                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1325
1326                let pending_range =
1327                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1328                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1329                    gutter_pending_ranges.push(pending_range);
1330                }
1331
1332                if let Some(edit_position) = codegen.edit_position(cx) {
1333                    let edited_range = assist.range.start..edit_position;
1334                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1335                        gutter_transformed_ranges.push(edited_range);
1336                    }
1337                }
1338
1339                if assist.decorations.is_some() {
1340                    inserted_row_ranges
1341                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1342                }
1343            }
1344        }
1345
1346        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1347        merge_ranges(&mut foreground_ranges, &snapshot);
1348        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1349        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1350        editor.update(cx, |editor, cx| {
1351            enum GutterPendingRange {}
1352            if gutter_pending_ranges.is_empty() {
1353                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1354            } else {
1355                editor.highlight_gutter::<GutterPendingRange>(
1356                    gutter_pending_ranges,
1357                    |cx| cx.theme().status().info_background,
1358                    cx,
1359                )
1360            }
1361
1362            enum GutterTransformedRange {}
1363            if gutter_transformed_ranges.is_empty() {
1364                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1365            } else {
1366                editor.highlight_gutter::<GutterTransformedRange>(
1367                    gutter_transformed_ranges,
1368                    |cx| cx.theme().status().info,
1369                    cx,
1370                )
1371            }
1372
1373            if foreground_ranges.is_empty() {
1374                editor.clear_highlights::<InlineAssist>(cx);
1375            } else {
1376                editor.highlight_text::<InlineAssist>(
1377                    foreground_ranges,
1378                    HighlightStyle {
1379                        fade_out: Some(0.6),
1380                        ..Default::default()
1381                    },
1382                    cx,
1383                );
1384            }
1385
1386            editor.clear_row_highlights::<InlineAssist>();
1387            for row_range in inserted_row_ranges {
1388                editor.highlight_rows::<InlineAssist>(
1389                    row_range,
1390                    cx.theme().status().info_background,
1391                    Default::default(),
1392                    cx,
1393                );
1394            }
1395        });
1396    }
1397
1398    fn update_editor_blocks(
1399        &mut self,
1400        editor: &Entity<Editor>,
1401        assist_id: InlineAssistId,
1402        window: &mut Window,
1403        cx: &mut App,
1404    ) {
1405        let Some(assist) = self.assists.get_mut(&assist_id) else {
1406            return;
1407        };
1408        let Some(decorations) = assist.decorations.as_mut() else {
1409            return;
1410        };
1411
1412        let codegen = assist.codegen.read(cx);
1413        let old_snapshot = codegen.snapshot(cx);
1414        let old_buffer = codegen.old_buffer(cx);
1415        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1416
1417        editor.update(cx, |editor, cx| {
1418            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1419            editor.remove_blocks(old_blocks, None, cx);
1420
1421            let mut new_blocks = Vec::new();
1422            for (new_row, old_row_range) in deleted_row_ranges {
1423                let (_, buffer_start) = old_snapshot
1424                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1425                    .unwrap();
1426                let (_, buffer_end) = old_snapshot
1427                    .point_to_buffer_offset(Point::new(
1428                        *old_row_range.end(),
1429                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1430                    ))
1431                    .unwrap();
1432
1433                let deleted_lines_editor = cx.new(|cx| {
1434                    let multi_buffer =
1435                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1436                    multi_buffer.update(cx, |multi_buffer, cx| {
1437                        multi_buffer.push_excerpts(
1438                            old_buffer.clone(),
1439                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1440                            cx,
1441                        );
1442                    });
1443
1444                    enum DeletedLines {}
1445                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1446                    editor.disable_scrollbars_and_minimap(window, cx);
1447                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1448                    editor.set_show_wrap_guides(false, cx);
1449                    editor.set_show_gutter(false, cx);
1450                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1451                    editor.set_read_only(true);
1452                    editor.set_show_edit_predictions(Some(false), window, cx);
1453                    editor.highlight_rows::<DeletedLines>(
1454                        Anchor::min()..Anchor::max(),
1455                        cx.theme().status().deleted_background,
1456                        Default::default(),
1457                        cx,
1458                    );
1459                    editor
1460                });
1461
1462                let height =
1463                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1464                new_blocks.push(BlockProperties {
1465                    placement: BlockPlacement::Above(new_row),
1466                    height: Some(height),
1467                    style: BlockStyle::Flex,
1468                    render: Arc::new(move |cx| {
1469                        div()
1470                            .block_mouse_except_scroll()
1471                            .bg(cx.theme().status().deleted_background)
1472                            .size_full()
1473                            .h(height as f32 * cx.window.line_height())
1474                            .pl(cx.margins.gutter.full_width())
1475                            .child(deleted_lines_editor.clone())
1476                            .into_any_element()
1477                    }),
1478                    priority: 0,
1479                });
1480            }
1481
1482            decorations.removed_line_block_ids = editor
1483                .insert_blocks(new_blocks, None, cx)
1484                .into_iter()
1485                .collect();
1486        })
1487    }
1488
1489    fn resolve_inline_assist_target(
1490        workspace: &mut Workspace,
1491        agent_panel: Option<Entity<AgentPanel>>,
1492        window: &mut Window,
1493        cx: &mut App,
1494    ) -> Option<InlineAssistTarget> {
1495        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx)
1496            && terminal_panel
1497                .read(cx)
1498                .focus_handle(cx)
1499                .contains_focused(window, cx)
1500            && let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1501                pane.read(cx)
1502                    .active_item()
1503                    .and_then(|t| t.downcast::<TerminalView>())
1504            })
1505        {
1506            return Some(InlineAssistTarget::Terminal(terminal_view));
1507        }
1508
1509        let context_editor = agent_panel
1510            .and_then(|panel| panel.read(cx).active_context_editor())
1511            .and_then(|editor| {
1512                let editor = &editor.read(cx).editor().clone();
1513                if editor.read(cx).is_focused(window) {
1514                    Some(editor.clone())
1515                } else {
1516                    None
1517                }
1518            });
1519
1520        if let Some(context_editor) = context_editor {
1521            Some(InlineAssistTarget::Editor(context_editor))
1522        } else if let Some(workspace_editor) = workspace
1523            .active_item(cx)
1524            .and_then(|item| item.act_as::<Editor>(cx))
1525        {
1526            Some(InlineAssistTarget::Editor(workspace_editor))
1527        } else {
1528            workspace
1529                .active_item(cx)
1530                .and_then(|item| item.act_as::<TerminalView>(cx))
1531                .map(InlineAssistTarget::Terminal)
1532        }
1533    }
1534}
1535
1536struct EditorInlineAssists {
1537    assist_ids: Vec<InlineAssistId>,
1538    scroll_lock: Option<InlineAssistScrollLock>,
1539    highlight_updates: watch::Sender<()>,
1540    _update_highlights: Task<Result<()>>,
1541    _subscriptions: Vec<gpui::Subscription>,
1542}
1543
1544struct InlineAssistScrollLock {
1545    assist_id: InlineAssistId,
1546    distance_from_top: f32,
1547}
1548
1549impl EditorInlineAssists {
1550    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1551        let (highlight_updates_tx, mut highlight_updates_rx) = watch::channel(());
1552        Self {
1553            assist_ids: Vec::new(),
1554            scroll_lock: None,
1555            highlight_updates: highlight_updates_tx,
1556            _update_highlights: cx.spawn({
1557                let editor = editor.downgrade();
1558                async move |cx| {
1559                    while let Ok(()) = highlight_updates_rx.changed().await {
1560                        let editor = editor.upgrade().context("editor was dropped")?;
1561                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1562                            assistant.update_editor_highlights(&editor, cx);
1563                        })?;
1564                    }
1565                    Ok(())
1566                }
1567            }),
1568            _subscriptions: vec![
1569                cx.observe_release_in(editor, window, {
1570                    let editor = editor.downgrade();
1571                    |_, window, cx| {
1572                        InlineAssistant::update_global(cx, |this, cx| {
1573                            this.handle_editor_release(editor, window, cx);
1574                        })
1575                    }
1576                }),
1577                window.observe(editor, cx, move |editor, window, cx| {
1578                    InlineAssistant::update_global(cx, |this, cx| {
1579                        this.handle_editor_change(editor, window, cx)
1580                    })
1581                }),
1582                window.subscribe(editor, cx, move |editor, event, window, cx| {
1583                    InlineAssistant::update_global(cx, |this, cx| {
1584                        this.handle_editor_event(editor, event, window, cx)
1585                    })
1586                }),
1587                editor.update(cx, |editor, cx| {
1588                    let editor_handle = cx.entity().downgrade();
1589                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1590                        InlineAssistant::update_global(cx, |this, cx| {
1591                            if let Some(editor) = editor_handle.upgrade() {
1592                                this.handle_editor_newline(editor, window, cx)
1593                            }
1594                        })
1595                    })
1596                }),
1597                editor.update(cx, |editor, cx| {
1598                    let editor_handle = cx.entity().downgrade();
1599                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1600                        InlineAssistant::update_global(cx, |this, cx| {
1601                            if let Some(editor) = editor_handle.upgrade() {
1602                                this.handle_editor_cancel(editor, window, cx)
1603                            }
1604                        })
1605                    })
1606                }),
1607            ],
1608        }
1609    }
1610}
1611
1612struct InlineAssistGroup {
1613    assist_ids: Vec<InlineAssistId>,
1614    linked: bool,
1615    active_assist_id: Option<InlineAssistId>,
1616}
1617
1618impl InlineAssistGroup {
1619    fn new() -> Self {
1620        Self {
1621            assist_ids: Vec::new(),
1622            linked: true,
1623            active_assist_id: None,
1624        }
1625    }
1626}
1627
1628fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1629    let editor = editor.clone();
1630
1631    Arc::new(move |cx: &mut BlockContext| {
1632        let editor_margins = editor.read(cx).editor_margins();
1633
1634        *editor_margins.lock() = *cx.margins;
1635        editor.clone().into_any_element()
1636    })
1637}
1638
1639#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1640struct InlineAssistGroupId(usize);
1641
1642impl InlineAssistGroupId {
1643    fn post_inc(&mut self) -> InlineAssistGroupId {
1644        let id = *self;
1645        self.0 += 1;
1646        id
1647    }
1648}
1649
1650pub struct InlineAssist {
1651    group_id: InlineAssistGroupId,
1652    range: Range<Anchor>,
1653    editor: WeakEntity<Editor>,
1654    decorations: Option<InlineAssistDecorations>,
1655    codegen: Entity<BufferCodegen>,
1656    _subscriptions: Vec<Subscription>,
1657    workspace: WeakEntity<Workspace>,
1658}
1659
1660impl InlineAssist {
1661    fn new(
1662        assist_id: InlineAssistId,
1663        group_id: InlineAssistGroupId,
1664        editor: &Entity<Editor>,
1665        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1666        prompt_block_id: CustomBlockId,
1667        end_block_id: CustomBlockId,
1668        range: Range<Anchor>,
1669        codegen: Entity<BufferCodegen>,
1670        workspace: WeakEntity<Workspace>,
1671        window: &mut Window,
1672        cx: &mut App,
1673    ) -> Self {
1674        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1675        InlineAssist {
1676            group_id,
1677            editor: editor.downgrade(),
1678            decorations: Some(InlineAssistDecorations {
1679                prompt_block_id,
1680                prompt_editor: prompt_editor.clone(),
1681                removed_line_block_ids: HashSet::default(),
1682                end_block_id,
1683            }),
1684            range,
1685            codegen: codegen.clone(),
1686            workspace,
1687            _subscriptions: vec![
1688                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1689                    InlineAssistant::update_global(cx, |this, cx| {
1690                        this.handle_prompt_editor_focus_in(assist_id, cx)
1691                    })
1692                }),
1693                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1694                    InlineAssistant::update_global(cx, |this, cx| {
1695                        this.handle_prompt_editor_focus_out(assist_id, cx)
1696                    })
1697                }),
1698                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1699                    InlineAssistant::update_global(cx, |this, cx| {
1700                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1701                    })
1702                }),
1703                window.observe(&codegen, cx, {
1704                    let editor = editor.downgrade();
1705                    move |_, window, cx| {
1706                        if let Some(editor) = editor.upgrade() {
1707                            InlineAssistant::update_global(cx, |this, cx| {
1708                                if let Some(editor_assists) =
1709                                    this.assists_by_editor.get_mut(&editor.downgrade())
1710                                {
1711                                    editor_assists.highlight_updates.send(()).ok();
1712                                }
1713
1714                                this.update_editor_blocks(&editor, assist_id, window, cx);
1715                            })
1716                        }
1717                    }
1718                }),
1719                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1720                    InlineAssistant::update_global(cx, |this, cx| match event {
1721                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1722                        CodegenEvent::Finished => {
1723                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1724                                assist
1725                            } else {
1726                                return;
1727                            };
1728
1729                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx)
1730                                && assist.decorations.is_none()
1731                                && let Some(workspace) = assist.workspace.upgrade()
1732                            {
1733                                let error = format!("Inline assistant error: {}", error);
1734                                workspace.update(cx, |workspace, cx| {
1735                                    struct InlineAssistantError;
1736
1737                                    let id = NotificationId::composite::<InlineAssistantError>(
1738                                        assist_id.0,
1739                                    );
1740
1741                                    workspace.show_toast(Toast::new(id, error), cx);
1742                                })
1743                            }
1744
1745                            if assist.decorations.is_none() {
1746                                this.finish_assist(assist_id, false, window, cx);
1747                            }
1748                        }
1749                    })
1750                }),
1751            ],
1752        }
1753    }
1754
1755    fn user_prompt(&self, cx: &App) -> Option<String> {
1756        let decorations = self.decorations.as_ref()?;
1757        Some(decorations.prompt_editor.read(cx).prompt(cx))
1758    }
1759}
1760
1761struct InlineAssistDecorations {
1762    prompt_block_id: CustomBlockId,
1763    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1764    removed_line_block_ids: HashSet<CustomBlockId>,
1765    end_block_id: CustomBlockId,
1766}
1767
1768struct AssistantCodeActionProvider {
1769    editor: WeakEntity<Editor>,
1770    workspace: WeakEntity<Workspace>,
1771    thread_store: Option<WeakEntity<ThreadStore>>,
1772    text_thread_store: Option<WeakEntity<TextThreadStore>>,
1773}
1774
1775const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant2";
1776
1777impl CodeActionProvider for AssistantCodeActionProvider {
1778    fn id(&self) -> Arc<str> {
1779        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1780    }
1781
1782    fn code_actions(
1783        &self,
1784        buffer: &Entity<Buffer>,
1785        range: Range<text::Anchor>,
1786        _: &mut Window,
1787        cx: &mut App,
1788    ) -> Task<Result<Vec<CodeAction>>> {
1789        if !AgentSettings::get_global(cx).enabled(cx) {
1790            return Task::ready(Ok(Vec::new()));
1791        }
1792
1793        let snapshot = buffer.read(cx).snapshot();
1794        let mut range = range.to_point(&snapshot);
1795
1796        // Expand the range to line boundaries.
1797        range.start.column = 0;
1798        range.end.column = snapshot.line_len(range.end.row);
1799
1800        let mut has_diagnostics = false;
1801        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1802            range.start = cmp::min(range.start, diagnostic.range.start);
1803            range.end = cmp::max(range.end, diagnostic.range.end);
1804            has_diagnostics = true;
1805        }
1806        if has_diagnostics {
1807            let symbols_containing_start = snapshot.symbols_containing(range.start, None);
1808            if let Some(symbol) = symbols_containing_start.last() {
1809                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1810                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1811            }
1812            let symbols_containing_end = snapshot.symbols_containing(range.end, None);
1813            if let Some(symbol) = symbols_containing_end.last() {
1814                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1815                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1816            }
1817
1818            Task::ready(Ok(vec![CodeAction {
1819                server_id: language::LanguageServerId(0),
1820                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1821                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1822                    title: "Fix with Assistant".into(),
1823                    ..Default::default()
1824                })),
1825                resolved: true,
1826            }]))
1827        } else {
1828            Task::ready(Ok(Vec::new()))
1829        }
1830    }
1831
1832    fn apply_code_action(
1833        &self,
1834        buffer: Entity<Buffer>,
1835        action: CodeAction,
1836        excerpt_id: ExcerptId,
1837        _push_to_history: bool,
1838        window: &mut Window,
1839        cx: &mut App,
1840    ) -> Task<Result<ProjectTransaction>> {
1841        let editor = self.editor.clone();
1842        let workspace = self.workspace.clone();
1843        let thread_store = self.thread_store.clone();
1844        let text_thread_store = self.text_thread_store.clone();
1845        let prompt_store = PromptStore::global(cx);
1846        window.spawn(cx, async move |cx| {
1847            let workspace = workspace.upgrade().context("workspace was released")?;
1848            let editor = editor.upgrade().context("editor was released")?;
1849            let range = editor
1850                .update(cx, |editor, cx| {
1851                    editor.buffer().update(cx, |multibuffer, cx| {
1852                        let buffer = buffer.read(cx);
1853                        let multibuffer_snapshot = multibuffer.read(cx);
1854
1855                        let old_context_range =
1856                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1857                        let mut new_context_range = old_context_range.clone();
1858                        if action
1859                            .range
1860                            .start
1861                            .cmp(&old_context_range.start, buffer)
1862                            .is_lt()
1863                        {
1864                            new_context_range.start = action.range.start;
1865                        }
1866                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1867                            new_context_range.end = action.range.end;
1868                        }
1869                        drop(multibuffer_snapshot);
1870
1871                        if new_context_range != old_context_range {
1872                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1873                        }
1874
1875                        let multibuffer_snapshot = multibuffer.read(cx);
1876                        Some(
1877                            multibuffer_snapshot
1878                                .anchor_in_excerpt(excerpt_id, action.range.start)?
1879                                ..multibuffer_snapshot
1880                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
1881                        )
1882                    })
1883                })?
1884                .context("invalid range")?;
1885
1886            let prompt_store = prompt_store.await.ok();
1887            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1888                let assist_id = assistant.suggest_assist(
1889                    &editor,
1890                    range,
1891                    "Fix Diagnostics".into(),
1892                    None,
1893                    true,
1894                    workspace,
1895                    prompt_store,
1896                    thread_store,
1897                    text_thread_store,
1898                    window,
1899                    cx,
1900                );
1901                assistant.start_assist(assist_id, window, cx);
1902            })?;
1903
1904            Ok(ProjectTransaction::default())
1905        })
1906    }
1907}
1908
1909fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1910    ranges.sort_unstable_by(|a, b| {
1911        a.start
1912            .cmp(&b.start, buffer)
1913            .then_with(|| b.end.cmp(&a.end, buffer))
1914    });
1915
1916    let mut ix = 0;
1917    while ix + 1 < ranges.len() {
1918        let b = ranges[ix + 1].clone();
1919        let a = &mut ranges[ix];
1920        if a.end.cmp(&b.start, buffer).is_gt() {
1921            if a.end.cmp(&b.end, buffer).is_lt() {
1922                a.end = b.end;
1923            }
1924            ranges.remove(ix + 1);
1925        } else {
1926            ix += 1;
1927        }
1928    }
1929}