inline_assistant.rs

   1use std::cmp;
   2use std::mem;
   3use std::ops::Range;
   4use std::rc::Rc;
   5use std::sync::Arc;
   6
   7use crate::{
   8    AgentPanel,
   9    buffer_codegen::{BufferCodegen, CodegenAlternative, CodegenEvent},
  10    context_store::ContextStore,
  11    inline_prompt_editor::{CodegenStatus, InlineAssistId, PromptEditor, PromptEditorEvent},
  12    terminal_inline_assistant::TerminalInlineAssistant,
  13};
  14use agent::HistoryStore;
  15use agent_settings::AgentSettings;
  16use anyhow::{Context as _, Result};
  17use client::telemetry::Telemetry;
  18use collections::{HashMap, HashSet, VecDeque, hash_map};
  19use editor::RowExt;
  20use editor::SelectionEffects;
  21use editor::scroll::ScrollOffset;
  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_ai_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_ai_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
 220                    editor.add_code_action_provider(
 221                        Rc::new(AssistantCodeActionProvider {
 222                            editor: cx.entity().downgrade(),
 223                            workspace: workspace.downgrade(),
 224                            thread_store,
 225                        }),
 226                        window,
 227                        cx,
 228                    );
 229
 230                    if DisableAiSettings::get_global(cx).disable_ai {
 231                        // Cancel any active edit predictions
 232                        if editor.has_active_edit_prediction() {
 233                            editor.cancel(&Default::default(), window, cx);
 234                        }
 235                    }
 236
 237                    // Remove the Assistant1 code action provider, as it still might be registered.
 238                    editor.remove_code_action_provider("assistant".into(), window, cx);
 239                } else {
 240                    editor.remove_code_action_provider(
 241                        ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
 242                        window,
 243                        cx,
 244                    );
 245                }
 246            });
 247        }
 248    }
 249
 250    pub fn inline_assist(
 251        workspace: &mut Workspace,
 252        action: &zed_actions::assistant::InlineAssist,
 253        window: &mut Window,
 254        cx: &mut Context<Workspace>,
 255    ) {
 256        if !AgentSettings::get_global(cx).enabled(cx) {
 257            return;
 258        }
 259
 260        let Some(inline_assist_target) = Self::resolve_inline_assist_target(
 261            workspace,
 262            workspace.panel::<AgentPanel>(cx),
 263            window,
 264            cx,
 265        ) else {
 266            return;
 267        };
 268
 269        let configuration_error = || {
 270            let model_registry = LanguageModelRegistry::read_global(cx);
 271            model_registry.configuration_error(model_registry.inline_assistant_model(), cx)
 272        };
 273
 274        let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) else {
 275            return;
 276        };
 277        let agent_panel = agent_panel.read(cx);
 278
 279        let prompt_store = agent_panel.prompt_store().as_ref().cloned();
 280        let thread_store = Some(agent_panel.thread_store().downgrade());
 281        let context_store = agent_panel.inline_assist_context_store().clone();
 282
 283        let handle_assist =
 284            |window: &mut Window, cx: &mut Context<Workspace>| match inline_assist_target {
 285                InlineAssistTarget::Editor(active_editor) => {
 286                    InlineAssistant::update_global(cx, |assistant, cx| {
 287                        assistant.assist(
 288                            &active_editor,
 289                            cx.entity().downgrade(),
 290                            context_store,
 291                            workspace.project().downgrade(),
 292                            prompt_store,
 293                            thread_store,
 294                            action.prompt.clone(),
 295                            window,
 296                            cx,
 297                        )
 298                    })
 299                }
 300                InlineAssistTarget::Terminal(active_terminal) => {
 301                    TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 302                        assistant.assist(
 303                            &active_terminal,
 304                            cx.entity().downgrade(),
 305                            workspace.project().downgrade(),
 306                            prompt_store,
 307                            thread_store,
 308                            action.prompt.clone(),
 309                            window,
 310                            cx,
 311                        )
 312                    })
 313                }
 314            };
 315
 316        if let Some(error) = configuration_error() {
 317            if let ConfigurationError::ProviderNotAuthenticated(provider) = error {
 318                cx.spawn(async move |_, cx| {
 319                    cx.update(|cx| provider.authenticate(cx))?.await?;
 320                    anyhow::Ok(())
 321                })
 322                .detach_and_log_err(cx);
 323
 324                if configuration_error().is_none() {
 325                    handle_assist(window, cx);
 326                }
 327            } else {
 328                cx.spawn_in(window, async move |_, cx| {
 329                    let answer = cx
 330                        .prompt(
 331                            gpui::PromptLevel::Warning,
 332                            &error.to_string(),
 333                            None,
 334                            &["Configure", "Cancel"],
 335                        )
 336                        .await
 337                        .ok();
 338                    if let Some(answer) = answer
 339                        && answer == 0
 340                    {
 341                        cx.update(|window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
 342                            .ok();
 343                    }
 344                    anyhow::Ok(())
 345                })
 346                .detach_and_log_err(cx);
 347            }
 348        } else {
 349            handle_assist(window, cx);
 350        }
 351    }
 352
 353    pub fn assist(
 354        &mut self,
 355        editor: &Entity<Editor>,
 356        workspace: WeakEntity<Workspace>,
 357        context_store: Entity<ContextStore>,
 358        project: WeakEntity<Project>,
 359        prompt_store: Option<Entity<PromptStore>>,
 360        thread_store: Option<WeakEntity<HistoryStore>>,
 361        initial_prompt: Option<String>,
 362        window: &mut Window,
 363        cx: &mut App,
 364    ) {
 365        let (snapshot, initial_selections, newest_selection) = editor.update(cx, |editor, cx| {
 366            let snapshot = editor.snapshot(window, cx);
 367            let selections = editor.selections.all::<Point>(&snapshot.display_snapshot);
 368            let newest_selection = editor
 369                .selections
 370                .newest::<Point>(&snapshot.display_snapshot);
 371            (snapshot, selections, newest_selection)
 372        });
 373
 374        // Check if there is already an inline assistant that contains the
 375        // newest selection, if there is, focus it
 376        if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 377            for assist_id in &editor_assists.assist_ids {
 378                let assist = &self.assists[assist_id];
 379                let range = assist.range.to_point(&snapshot.buffer_snapshot());
 380                if range.start.row <= newest_selection.start.row
 381                    && newest_selection.end.row <= range.end.row
 382                {
 383                    self.focus_assist(*assist_id, window, cx);
 384                    return;
 385                }
 386            }
 387        }
 388
 389        let mut selections = Vec::<Selection<Point>>::new();
 390        let mut newest_selection = None;
 391        for mut selection in initial_selections {
 392            if selection.end > selection.start {
 393                selection.start.column = 0;
 394                // If the selection ends at the start of the line, we don't want to include it.
 395                if selection.end.column == 0 {
 396                    selection.end.row -= 1;
 397                }
 398                selection.end.column = snapshot
 399                    .buffer_snapshot()
 400                    .line_len(MultiBufferRow(selection.end.row));
 401            } else if let Some(fold) =
 402                snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
 403            {
 404                selection.start = fold.range().start;
 405                selection.end = fold.range().end;
 406                if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot().max_row() {
 407                    let chars = snapshot
 408                        .buffer_snapshot()
 409                        .chars_at(Point::new(selection.end.row + 1, 0));
 410
 411                    for c in chars {
 412                        if c == '\n' {
 413                            break;
 414                        }
 415                        if c.is_whitespace() {
 416                            continue;
 417                        }
 418                        if snapshot
 419                            .language_at(selection.end)
 420                            .is_some_and(|language| language.config().brackets.is_closing_brace(c))
 421                        {
 422                            selection.end.row += 1;
 423                            selection.end.column = snapshot
 424                                .buffer_snapshot()
 425                                .line_len(MultiBufferRow(selection.end.row));
 426                        }
 427                    }
 428                }
 429            }
 430
 431            if let Some(prev_selection) = selections.last_mut()
 432                && selection.start <= prev_selection.end
 433            {
 434                prev_selection.end = selection.end;
 435                continue;
 436            }
 437
 438            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 439            if selection.id > latest_selection.id {
 440                *latest_selection = selection.clone();
 441            }
 442            selections.push(selection);
 443        }
 444        let snapshot = &snapshot.buffer_snapshot();
 445        let newest_selection = newest_selection.unwrap();
 446
 447        let mut codegen_ranges = Vec::new();
 448        for (buffer, buffer_range, excerpt_id) in
 449            snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
 450                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 451            }))
 452        {
 453            let anchor_range = Anchor::range_in_buffer(
 454                excerpt_id,
 455                buffer.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
 456            );
 457
 458            codegen_ranges.push(anchor_range);
 459
 460            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
 461                self.telemetry.report_assistant_event(AssistantEventData {
 462                    conversation_id: None,
 463                    kind: AssistantKind::Inline,
 464                    phase: AssistantPhase::Invoked,
 465                    message_id: None,
 466                    model: model.model.telemetry_id(),
 467                    model_provider: model.provider.id().to_string(),
 468                    response_latency: None,
 469                    error_message: None,
 470                    language_name: buffer.language().map(|language| language.name().to_proto()),
 471                });
 472            }
 473        }
 474
 475        let assist_group_id = self.next_assist_group_id.post_inc();
 476        let prompt_buffer = cx.new(|cx| {
 477            MultiBuffer::singleton(
 478                cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
 479                cx,
 480            )
 481        });
 482
 483        let mut assists = Vec::new();
 484        let mut assist_to_focus = None;
 485        for range in codegen_ranges {
 486            let assist_id = self.next_assist_id.post_inc();
 487            let codegen = cx.new(|cx| {
 488                BufferCodegen::new(
 489                    editor.read(cx).buffer().clone(),
 490                    range.clone(),
 491                    None,
 492                    context_store.clone(),
 493                    project.clone(),
 494                    prompt_store.clone(),
 495                    self.telemetry.clone(),
 496                    self.prompt_builder.clone(),
 497                    cx,
 498                )
 499            });
 500
 501            let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 502            let prompt_editor = cx.new(|cx| {
 503                PromptEditor::new_buffer(
 504                    assist_id,
 505                    editor_margins,
 506                    self.prompt_history.clone(),
 507                    prompt_buffer.clone(),
 508                    codegen.clone(),
 509                    self.fs.clone(),
 510                    context_store.clone(),
 511                    workspace.clone(),
 512                    thread_store.clone(),
 513                    prompt_store.as_ref().map(|s| s.downgrade()),
 514                    window,
 515                    cx,
 516                )
 517            });
 518
 519            if assist_to_focus.is_none() {
 520                let focus_assist = if newest_selection.reversed {
 521                    range.start.to_point(snapshot) == newest_selection.start
 522                } else {
 523                    range.end.to_point(snapshot) == newest_selection.end
 524                };
 525                if focus_assist {
 526                    assist_to_focus = Some(assist_id);
 527                }
 528            }
 529
 530            let [prompt_block_id, end_block_id] =
 531                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 532
 533            assists.push((
 534                assist_id,
 535                range,
 536                prompt_editor,
 537                prompt_block_id,
 538                end_block_id,
 539            ));
 540        }
 541
 542        let editor_assists = self
 543            .assists_by_editor
 544            .entry(editor.downgrade())
 545            .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
 546        let mut assist_group = InlineAssistGroup::new();
 547        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
 548            let codegen = prompt_editor.read(cx).codegen().clone();
 549
 550            self.assists.insert(
 551                assist_id,
 552                InlineAssist::new(
 553                    assist_id,
 554                    assist_group_id,
 555                    editor,
 556                    &prompt_editor,
 557                    prompt_block_id,
 558                    end_block_id,
 559                    range,
 560                    codegen,
 561                    workspace.clone(),
 562                    window,
 563                    cx,
 564                ),
 565            );
 566            assist_group.assist_ids.push(assist_id);
 567            editor_assists.assist_ids.push(assist_id);
 568        }
 569        self.assist_groups.insert(assist_group_id, assist_group);
 570
 571        if let Some(assist_id) = assist_to_focus {
 572            self.focus_assist(assist_id, window, cx);
 573        }
 574    }
 575
 576    pub fn suggest_assist(
 577        &mut self,
 578        editor: &Entity<Editor>,
 579        mut range: Range<Anchor>,
 580        initial_prompt: String,
 581        initial_transaction_id: Option<TransactionId>,
 582        focus: bool,
 583        workspace: Entity<Workspace>,
 584        prompt_store: Option<Entity<PromptStore>>,
 585        thread_store: Option<WeakEntity<HistoryStore>>,
 586        window: &mut Window,
 587        cx: &mut App,
 588    ) -> InlineAssistId {
 589        let assist_group_id = self.next_assist_group_id.post_inc();
 590        let prompt_buffer = cx.new(|cx| Buffer::local(&initial_prompt, cx));
 591        let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 592
 593        let assist_id = self.next_assist_id.post_inc();
 594
 595        let buffer = editor.read(cx).buffer().clone();
 596        {
 597            let snapshot = buffer.read(cx).read(cx);
 598            range.start = range.start.bias_left(&snapshot);
 599            range.end = range.end.bias_right(&snapshot);
 600        }
 601
 602        let project = workspace.read(cx).project().downgrade();
 603        let context_store = cx.new(|_cx| ContextStore::new(project.clone()));
 604
 605        let codegen = cx.new(|cx| {
 606            BufferCodegen::new(
 607                editor.read(cx).buffer().clone(),
 608                range.clone(),
 609                initial_transaction_id,
 610                context_store.clone(),
 611                project,
 612                prompt_store.clone(),
 613                self.telemetry.clone(),
 614                self.prompt_builder.clone(),
 615                cx,
 616            )
 617        });
 618
 619        let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 620        let prompt_editor = cx.new(|cx| {
 621            PromptEditor::new_buffer(
 622                assist_id,
 623                editor_margins,
 624                self.prompt_history.clone(),
 625                prompt_buffer.clone(),
 626                codegen.clone(),
 627                self.fs.clone(),
 628                context_store,
 629                workspace.downgrade(),
 630                thread_store,
 631                prompt_store.map(|s| s.downgrade()),
 632                window,
 633                cx,
 634            )
 635        });
 636
 637        let [prompt_block_id, end_block_id] =
 638            self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 639
 640        let editor_assists = self
 641            .assists_by_editor
 642            .entry(editor.downgrade())
 643            .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
 644
 645        let mut assist_group = InlineAssistGroup::new();
 646        self.assists.insert(
 647            assist_id,
 648            InlineAssist::new(
 649                assist_id,
 650                assist_group_id,
 651                editor,
 652                &prompt_editor,
 653                prompt_block_id,
 654                end_block_id,
 655                range,
 656                codegen.clone(),
 657                workspace.downgrade(),
 658                window,
 659                cx,
 660            ),
 661        );
 662        assist_group.assist_ids.push(assist_id);
 663        editor_assists.assist_ids.push(assist_id);
 664        self.assist_groups.insert(assist_group_id, assist_group);
 665
 666        if focus {
 667            self.focus_assist(assist_id, window, cx);
 668        }
 669
 670        assist_id
 671    }
 672
 673    fn insert_assist_blocks(
 674        &self,
 675        editor: &Entity<Editor>,
 676        range: &Range<Anchor>,
 677        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
 678        cx: &mut App,
 679    ) -> [CustomBlockId; 2] {
 680        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 681            prompt_editor
 682                .editor
 683                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 684        });
 685        let assist_blocks = vec![
 686            BlockProperties {
 687                style: BlockStyle::Sticky,
 688                placement: BlockPlacement::Above(range.start),
 689                height: Some(prompt_editor_height),
 690                render: build_assist_editor_renderer(prompt_editor),
 691                priority: 0,
 692            },
 693            BlockProperties {
 694                style: BlockStyle::Sticky,
 695                placement: BlockPlacement::Below(range.end),
 696                height: None,
 697                render: Arc::new(|cx| {
 698                    v_flex()
 699                        .h_full()
 700                        .w_full()
 701                        .border_t_1()
 702                        .border_color(cx.theme().status().info_border)
 703                        .into_any_element()
 704                }),
 705                priority: 0,
 706            },
 707        ];
 708
 709        editor.update(cx, |editor, cx| {
 710            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 711            [block_ids[0], block_ids[1]]
 712        })
 713    }
 714
 715    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 716        let assist = &self.assists[&assist_id];
 717        let Some(decorations) = assist.decorations.as_ref() else {
 718            return;
 719        };
 720        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 721        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 722
 723        assist_group.active_assist_id = Some(assist_id);
 724        if assist_group.linked {
 725            for assist_id in &assist_group.assist_ids {
 726                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 727                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 728                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 729                    });
 730                }
 731            }
 732        }
 733
 734        assist
 735            .editor
 736            .update(cx, |editor, cx| {
 737                let scroll_top = editor.scroll_position(cx).y;
 738                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 739                editor_assists.scroll_lock = editor
 740                    .row_for_block(decorations.prompt_block_id, cx)
 741                    .map(|row| row.as_f64())
 742                    .filter(|prompt_row| (scroll_top..scroll_bottom).contains(&prompt_row))
 743                    .map(|prompt_row| InlineAssistScrollLock {
 744                        assist_id,
 745                        distance_from_top: prompt_row - scroll_top,
 746                    });
 747            })
 748            .ok();
 749    }
 750
 751    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 752        let assist = &self.assists[&assist_id];
 753        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 754        if assist_group.active_assist_id == Some(assist_id) {
 755            assist_group.active_assist_id = None;
 756            if assist_group.linked {
 757                for assist_id in &assist_group.assist_ids {
 758                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 759                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 760                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 761                        });
 762                    }
 763                }
 764            }
 765        }
 766    }
 767
 768    fn handle_prompt_editor_event(
 769        &mut self,
 770        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 771        event: &PromptEditorEvent,
 772        window: &mut Window,
 773        cx: &mut App,
 774    ) {
 775        let assist_id = prompt_editor.read(cx).id();
 776        match event {
 777            PromptEditorEvent::StartRequested => {
 778                self.start_assist(assist_id, window, cx);
 779            }
 780            PromptEditorEvent::StopRequested => {
 781                self.stop_assist(assist_id, cx);
 782            }
 783            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 784                self.finish_assist(assist_id, false, window, cx);
 785            }
 786            PromptEditorEvent::CancelRequested => {
 787                self.finish_assist(assist_id, true, window, cx);
 788            }
 789            PromptEditorEvent::Resized { .. } => {
 790                // This only matters for the terminal inline assistant
 791            }
 792        }
 793    }
 794
 795    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 796        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 797            return;
 798        };
 799
 800        if editor.read(cx).selections.count() == 1 {
 801            let (selection, buffer) = editor.update(cx, |editor, cx| {
 802                (
 803                    editor
 804                        .selections
 805                        .newest::<usize>(&editor.display_snapshot(cx)),
 806                    editor.buffer().read(cx).snapshot(cx),
 807                )
 808            });
 809            for assist_id in &editor_assists.assist_ids {
 810                let assist = &self.assists[assist_id];
 811                let assist_range = assist.range.to_offset(&buffer);
 812                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 813                {
 814                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 815                        self.dismiss_assist(*assist_id, window, cx);
 816                    } else {
 817                        self.finish_assist(*assist_id, false, window, cx);
 818                    }
 819
 820                    return;
 821                }
 822            }
 823        }
 824
 825        cx.propagate();
 826    }
 827
 828    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 829        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 830            return;
 831        };
 832
 833        if editor.read(cx).selections.count() == 1 {
 834            let (selection, buffer) = editor.update(cx, |editor, cx| {
 835                (
 836                    editor
 837                        .selections
 838                        .newest::<usize>(&editor.display_snapshot(cx)),
 839                    editor.buffer().read(cx).snapshot(cx),
 840                )
 841            });
 842            let mut closest_assist_fallback = None;
 843            for assist_id in &editor_assists.assist_ids {
 844                let assist = &self.assists[assist_id];
 845                let assist_range = assist.range.to_offset(&buffer);
 846                if assist.decorations.is_some() {
 847                    if assist_range.contains(&selection.start)
 848                        && assist_range.contains(&selection.end)
 849                    {
 850                        self.focus_assist(*assist_id, window, cx);
 851                        return;
 852                    } else {
 853                        let distance_from_selection = assist_range
 854                            .start
 855                            .abs_diff(selection.start)
 856                            .min(assist_range.start.abs_diff(selection.end))
 857                            + assist_range
 858                                .end
 859                                .abs_diff(selection.start)
 860                                .min(assist_range.end.abs_diff(selection.end));
 861                        match closest_assist_fallback {
 862                            Some((_, old_distance)) => {
 863                                if distance_from_selection < old_distance {
 864                                    closest_assist_fallback =
 865                                        Some((assist_id, distance_from_selection));
 866                                }
 867                            }
 868                            None => {
 869                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 870                            }
 871                        }
 872                    }
 873                }
 874            }
 875
 876            if let Some((&assist_id, _)) = closest_assist_fallback {
 877                self.focus_assist(assist_id, window, cx);
 878            }
 879        }
 880
 881        cx.propagate();
 882    }
 883
 884    fn handle_editor_release(
 885        &mut self,
 886        editor: WeakEntity<Editor>,
 887        window: &mut Window,
 888        cx: &mut App,
 889    ) {
 890        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 891            for assist_id in editor_assists.assist_ids.clone() {
 892                self.finish_assist(assist_id, true, window, cx);
 893            }
 894        }
 895    }
 896
 897    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 898        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 899            return;
 900        };
 901        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 902            return;
 903        };
 904        let assist = &self.assists[&scroll_lock.assist_id];
 905        let Some(decorations) = assist.decorations.as_ref() else {
 906            return;
 907        };
 908
 909        editor.update(cx, |editor, cx| {
 910            let scroll_position = editor.scroll_position(cx);
 911            let target_scroll_top = editor
 912                .row_for_block(decorations.prompt_block_id, cx)?
 913                .as_f64()
 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 = editor
 963                                .row_for_block(decorations.prompt_block_id, cx)?
 964                                .0 as ScrollOffset;
 965                            Some(prompt_row - scroll_top)
 966                        });
 967
 968                        if distance_from_top.is_none_or(|distance_from_top| {
 969                            distance_from_top != scroll_lock.distance_from_top
 970                        }) {
 971                            editor_assists.scroll_lock = None;
 972                        }
 973                    }
 974                }
 975            }
 976            EditorEvent::SelectionsChanged { .. } => {
 977                for assist_id in editor_assists.assist_ids.clone() {
 978                    let assist = &self.assists[&assist_id];
 979                    if let Some(decorations) = assist.decorations.as_ref()
 980                        && decorations
 981                            .prompt_editor
 982                            .focus_handle(cx)
 983                            .is_focused(window)
 984                    {
 985                        return;
 986                    }
 987                }
 988
 989                editor_assists.scroll_lock = None;
 990            }
 991            _ => {}
 992        }
 993    }
 994
 995    pub fn finish_assist(
 996        &mut self,
 997        assist_id: InlineAssistId,
 998        undo: bool,
 999        window: &mut Window,
1000        cx: &mut App,
1001    ) {
1002        if let Some(assist) = self.assists.get(&assist_id) {
1003            let assist_group_id = assist.group_id;
1004            if self.assist_groups[&assist_group_id].linked {
1005                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1006                    self.finish_assist(assist_id, undo, window, cx);
1007                }
1008                return;
1009            }
1010        }
1011
1012        self.dismiss_assist(assist_id, window, cx);
1013
1014        if let Some(assist) = self.assists.remove(&assist_id) {
1015            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
1016            {
1017                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1018                if entry.get().assist_ids.is_empty() {
1019                    entry.remove();
1020                }
1021            }
1022
1023            if let hash_map::Entry::Occupied(mut entry) =
1024                self.assists_by_editor.entry(assist.editor.clone())
1025            {
1026                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1027                if entry.get().assist_ids.is_empty() {
1028                    entry.remove();
1029                    if let Some(editor) = assist.editor.upgrade() {
1030                        self.update_editor_highlights(&editor, cx);
1031                    }
1032                } else {
1033                    entry.get_mut().highlight_updates.send(()).ok();
1034                }
1035            }
1036
1037            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1038            let message_id = active_alternative.read(cx).message_id.clone();
1039
1040            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1041                let language_name = assist.editor.upgrade().and_then(|editor| {
1042                    let multibuffer = editor.read(cx).buffer().read(cx);
1043                    let snapshot = multibuffer.snapshot(cx);
1044                    let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
1045                    ranges
1046                        .first()
1047                        .and_then(|(buffer, _, _)| buffer.language())
1048                        .map(|language| language.name())
1049                });
1050                report_assistant_event(
1051                    AssistantEventData {
1052                        conversation_id: None,
1053                        kind: AssistantKind::Inline,
1054                        message_id,
1055                        phase: if undo {
1056                            AssistantPhase::Rejected
1057                        } else {
1058                            AssistantPhase::Accepted
1059                        },
1060                        model: model.model.telemetry_id(),
1061                        model_provider: model.model.provider_id().to_string(),
1062                        response_latency: None,
1063                        error_message: None,
1064                        language_name: language_name.map(|name| name.to_proto()),
1065                    },
1066                    Some(self.telemetry.clone()),
1067                    cx.http_client(),
1068                    model.model.api_key(cx),
1069                    cx.background_executor(),
1070                );
1071            }
1072
1073            if undo {
1074                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1075            } else {
1076                self.confirmed_assists.insert(assist_id, active_alternative);
1077            }
1078        }
1079    }
1080
1081    fn dismiss_assist(
1082        &mut self,
1083        assist_id: InlineAssistId,
1084        window: &mut Window,
1085        cx: &mut App,
1086    ) -> bool {
1087        let Some(assist) = self.assists.get_mut(&assist_id) else {
1088            return false;
1089        };
1090        let Some(editor) = assist.editor.upgrade() else {
1091            return false;
1092        };
1093        let Some(decorations) = assist.decorations.take() else {
1094            return false;
1095        };
1096
1097        editor.update(cx, |editor, cx| {
1098            let mut to_remove = decorations.removed_line_block_ids;
1099            to_remove.insert(decorations.prompt_block_id);
1100            to_remove.insert(decorations.end_block_id);
1101            editor.remove_blocks(to_remove, None, cx);
1102        });
1103
1104        if decorations
1105            .prompt_editor
1106            .focus_handle(cx)
1107            .contains_focused(window, cx)
1108        {
1109            self.focus_next_assist(assist_id, window, cx);
1110        }
1111
1112        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1113            if editor_assists
1114                .scroll_lock
1115                .as_ref()
1116                .is_some_and(|lock| lock.assist_id == assist_id)
1117            {
1118                editor_assists.scroll_lock = None;
1119            }
1120            editor_assists.highlight_updates.send(()).ok();
1121        }
1122
1123        true
1124    }
1125
1126    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1127        let Some(assist) = self.assists.get(&assist_id) else {
1128            return;
1129        };
1130
1131        let assist_group = &self.assist_groups[&assist.group_id];
1132        let assist_ix = assist_group
1133            .assist_ids
1134            .iter()
1135            .position(|id| *id == assist_id)
1136            .unwrap();
1137        let assist_ids = assist_group
1138            .assist_ids
1139            .iter()
1140            .skip(assist_ix + 1)
1141            .chain(assist_group.assist_ids.iter().take(assist_ix));
1142
1143        for assist_id in assist_ids {
1144            let assist = &self.assists[assist_id];
1145            if assist.decorations.is_some() {
1146                self.focus_assist(*assist_id, window, cx);
1147                return;
1148            }
1149        }
1150
1151        assist
1152            .editor
1153            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1154            .ok();
1155    }
1156
1157    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1158        let Some(assist) = self.assists.get(&assist_id) else {
1159            return;
1160        };
1161
1162        if let Some(decorations) = assist.decorations.as_ref() {
1163            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1164                prompt_editor.editor.update(cx, |editor, cx| {
1165                    window.focus(&editor.focus_handle(cx));
1166                    editor.select_all(&SelectAll, window, cx);
1167                })
1168            });
1169        }
1170
1171        self.scroll_to_assist(assist_id, window, cx);
1172    }
1173
1174    pub fn scroll_to_assist(
1175        &mut self,
1176        assist_id: InlineAssistId,
1177        window: &mut Window,
1178        cx: &mut App,
1179    ) {
1180        let Some(assist) = self.assists.get(&assist_id) else {
1181            return;
1182        };
1183        let Some(editor) = assist.editor.upgrade() else {
1184            return;
1185        };
1186
1187        let position = assist.range.start;
1188        editor.update(cx, |editor, cx| {
1189            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1190                selections.select_anchor_ranges([position..position])
1191            });
1192
1193            let mut scroll_target_range = None;
1194            if let Some(decorations) = assist.decorations.as_ref() {
1195                scroll_target_range = maybe!({
1196                    let top = editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f64;
1197                    let bottom = editor.row_for_block(decorations.end_block_id, cx)?.0 as f64;
1198                    Some((top, bottom))
1199                });
1200                if scroll_target_range.is_none() {
1201                    log::error!("bug: failed to find blocks for scrolling to inline assist");
1202                }
1203            }
1204            let scroll_target_range = scroll_target_range.unwrap_or_else(|| {
1205                let snapshot = editor.snapshot(window, cx);
1206                let start_row = assist
1207                    .range
1208                    .start
1209                    .to_display_point(&snapshot.display_snapshot)
1210                    .row();
1211                let top = start_row.0 as ScrollOffset;
1212                let bottom = top + 1.0;
1213                (top, bottom)
1214            });
1215            let mut scroll_target_top = scroll_target_range.0;
1216            let mut scroll_target_bottom = scroll_target_range.1;
1217
1218            scroll_target_top -= editor.vertical_scroll_margin() as ScrollOffset;
1219            scroll_target_bottom += editor.vertical_scroll_margin() as ScrollOffset;
1220
1221            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1222            let scroll_top = editor.scroll_position(cx).y;
1223            let scroll_bottom = scroll_top + height_in_lines;
1224
1225            if scroll_target_top < scroll_top {
1226                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1227            } else if scroll_target_bottom > scroll_bottom {
1228                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1229                    editor.set_scroll_position(
1230                        point(0., scroll_target_bottom - height_in_lines),
1231                        window,
1232                        cx,
1233                    );
1234                } else {
1235                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1236                }
1237            }
1238        });
1239    }
1240
1241    fn unlink_assist_group(
1242        &mut self,
1243        assist_group_id: InlineAssistGroupId,
1244        window: &mut Window,
1245        cx: &mut App,
1246    ) -> Vec<InlineAssistId> {
1247        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1248        assist_group.linked = false;
1249
1250        for assist_id in &assist_group.assist_ids {
1251            let assist = self.assists.get_mut(assist_id).unwrap();
1252            if let Some(editor_decorations) = assist.decorations.as_ref() {
1253                editor_decorations
1254                    .prompt_editor
1255                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1256            }
1257        }
1258        assist_group.assist_ids.clone()
1259    }
1260
1261    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1262        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1263            assist
1264        } else {
1265            return;
1266        };
1267
1268        let assist_group_id = assist.group_id;
1269        if self.assist_groups[&assist_group_id].linked {
1270            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1271                self.start_assist(assist_id, window, cx);
1272            }
1273            return;
1274        }
1275
1276        let Some(user_prompt) = assist.user_prompt(cx) else {
1277            return;
1278        };
1279
1280        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1281        self.prompt_history.push_back(user_prompt.clone());
1282        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1283            self.prompt_history.pop_front();
1284        }
1285
1286        let Some(ConfiguredModel { model, .. }) =
1287            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1288        else {
1289            return;
1290        };
1291
1292        assist
1293            .codegen
1294            .update(cx, |codegen, cx| codegen.start(model, user_prompt, cx))
1295            .log_err();
1296    }
1297
1298    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1299        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1300            assist
1301        } else {
1302            return;
1303        };
1304
1305        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1306    }
1307
1308    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1309        let mut gutter_pending_ranges = Vec::new();
1310        let mut gutter_transformed_ranges = Vec::new();
1311        let mut foreground_ranges = Vec::new();
1312        let mut inserted_row_ranges = Vec::new();
1313        let empty_assist_ids = Vec::new();
1314        let assist_ids = self
1315            .assists_by_editor
1316            .get(&editor.downgrade())
1317            .map_or(&empty_assist_ids, |editor_assists| {
1318                &editor_assists.assist_ids
1319            });
1320
1321        for assist_id in assist_ids {
1322            if let Some(assist) = self.assists.get(assist_id) {
1323                let codegen = assist.codegen.read(cx);
1324                let buffer = codegen.buffer(cx).read(cx).read(cx);
1325                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1326
1327                let pending_range =
1328                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1329                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1330                    gutter_pending_ranges.push(pending_range);
1331                }
1332
1333                if let Some(edit_position) = codegen.edit_position(cx) {
1334                    let edited_range = assist.range.start..edit_position;
1335                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1336                        gutter_transformed_ranges.push(edited_range);
1337                    }
1338                }
1339
1340                if assist.decorations.is_some() {
1341                    inserted_row_ranges
1342                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1343                }
1344            }
1345        }
1346
1347        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1348        merge_ranges(&mut foreground_ranges, &snapshot);
1349        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1350        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1351        editor.update(cx, |editor, cx| {
1352            enum GutterPendingRange {}
1353            if gutter_pending_ranges.is_empty() {
1354                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1355            } else {
1356                editor.highlight_gutter::<GutterPendingRange>(
1357                    gutter_pending_ranges,
1358                    |cx| cx.theme().status().info_background,
1359                    cx,
1360                )
1361            }
1362
1363            enum GutterTransformedRange {}
1364            if gutter_transformed_ranges.is_empty() {
1365                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1366            } else {
1367                editor.highlight_gutter::<GutterTransformedRange>(
1368                    gutter_transformed_ranges,
1369                    |cx| cx.theme().status().info,
1370                    cx,
1371                )
1372            }
1373
1374            if foreground_ranges.is_empty() {
1375                editor.clear_highlights::<InlineAssist>(cx);
1376            } else {
1377                editor.highlight_text::<InlineAssist>(
1378                    foreground_ranges,
1379                    HighlightStyle {
1380                        fade_out: Some(0.6),
1381                        ..Default::default()
1382                    },
1383                    cx,
1384                );
1385            }
1386
1387            editor.clear_row_highlights::<InlineAssist>();
1388            for row_range in inserted_row_ranges {
1389                editor.highlight_rows::<InlineAssist>(
1390                    row_range,
1391                    cx.theme().status().info_background,
1392                    Default::default(),
1393                    cx,
1394                );
1395            }
1396        });
1397    }
1398
1399    fn update_editor_blocks(
1400        &mut self,
1401        editor: &Entity<Editor>,
1402        assist_id: InlineAssistId,
1403        window: &mut Window,
1404        cx: &mut App,
1405    ) {
1406        let Some(assist) = self.assists.get_mut(&assist_id) else {
1407            return;
1408        };
1409        let Some(decorations) = assist.decorations.as_mut() else {
1410            return;
1411        };
1412
1413        let codegen = assist.codegen.read(cx);
1414        let old_snapshot = codegen.snapshot(cx);
1415        let old_buffer = codegen.old_buffer(cx);
1416        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1417
1418        editor.update(cx, |editor, cx| {
1419            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1420            editor.remove_blocks(old_blocks, None, cx);
1421
1422            let mut new_blocks = Vec::new();
1423            for (new_row, old_row_range) in deleted_row_ranges {
1424                let (_, buffer_start) = old_snapshot
1425                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1426                    .unwrap();
1427                let (_, buffer_end) = old_snapshot
1428                    .point_to_buffer_offset(Point::new(
1429                        *old_row_range.end(),
1430                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1431                    ))
1432                    .unwrap();
1433
1434                let deleted_lines_editor = cx.new(|cx| {
1435                    let multi_buffer =
1436                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1437                    multi_buffer.update(cx, |multi_buffer, cx| {
1438                        multi_buffer.push_excerpts(
1439                            old_buffer.clone(),
1440                            // todo(lw): buffer_start and buffer_end might come from different snapshots!
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 text_thread_editor = agent_panel
1512            .and_then(|panel| panel.read(cx).active_text_thread_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(text_thread_editor) = text_thread_editor {
1523            Some(InlineAssistTarget::Editor(text_thread_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: ScrollOffset,
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<HistoryStore>>,
1774}
1775
1776const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant2";
1777
1778impl CodeActionProvider for AssistantCodeActionProvider {
1779    fn id(&self) -> Arc<str> {
1780        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1781    }
1782
1783    fn code_actions(
1784        &self,
1785        buffer: &Entity<Buffer>,
1786        range: Range<text::Anchor>,
1787        _: &mut Window,
1788        cx: &mut App,
1789    ) -> Task<Result<Vec<CodeAction>>> {
1790        if !AgentSettings::get_global(cx).enabled(cx) {
1791            return Task::ready(Ok(Vec::new()));
1792        }
1793
1794        let snapshot = buffer.read(cx).snapshot();
1795        let mut range = range.to_point(&snapshot);
1796
1797        // Expand the range to line boundaries.
1798        range.start.column = 0;
1799        range.end.column = snapshot.line_len(range.end.row);
1800
1801        let mut has_diagnostics = false;
1802        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1803            range.start = cmp::min(range.start, diagnostic.range.start);
1804            range.end = cmp::max(range.end, diagnostic.range.end);
1805            has_diagnostics = true;
1806        }
1807        if has_diagnostics {
1808            let symbols_containing_start = snapshot.symbols_containing(range.start, None);
1809            if let Some(symbol) = symbols_containing_start.last() {
1810                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1811                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1812            }
1813            let symbols_containing_end = snapshot.symbols_containing(range.end, None);
1814            if let Some(symbol) = symbols_containing_end.last() {
1815                range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1816                range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1817            }
1818
1819            Task::ready(Ok(vec![CodeAction {
1820                server_id: language::LanguageServerId(0),
1821                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1822                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1823                    title: "Fix with Assistant".into(),
1824                    ..Default::default()
1825                })),
1826                resolved: true,
1827            }]))
1828        } else {
1829            Task::ready(Ok(Vec::new()))
1830        }
1831    }
1832
1833    fn apply_code_action(
1834        &self,
1835        buffer: Entity<Buffer>,
1836        action: CodeAction,
1837        excerpt_id: ExcerptId,
1838        _push_to_history: bool,
1839        window: &mut Window,
1840        cx: &mut App,
1841    ) -> Task<Result<ProjectTransaction>> {
1842        let editor = self.editor.clone();
1843        let workspace = self.workspace.clone();
1844        let thread_store = self.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                        multibuffer_snapshot.anchor_range_in_excerpt(excerpt_id, action.range)
1877                    })
1878                })?
1879                .context("invalid range")?;
1880
1881            let prompt_store = prompt_store.await.ok();
1882            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1883                let assist_id = assistant.suggest_assist(
1884                    &editor,
1885                    range,
1886                    "Fix Diagnostics".into(),
1887                    None,
1888                    true,
1889                    workspace,
1890                    prompt_store,
1891                    thread_store,
1892                    window,
1893                    cx,
1894                );
1895                assistant.start_assist(assist_id, window, cx);
1896            })?;
1897
1898            Ok(ProjectTransaction::default())
1899        })
1900    }
1901}
1902
1903fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1904    ranges.sort_unstable_by(|a, b| {
1905        a.start
1906            .cmp(&b.start, buffer)
1907            .then_with(|| b.end.cmp(&a.end, buffer))
1908    });
1909
1910    let mut ix = 0;
1911    while ix + 1 < ranges.len() {
1912        let b = ranges[ix + 1].clone();
1913        let a = &mut ranges[ix];
1914        if a.end.cmp(&b.start, buffer).is_gt() {
1915            if a.end.cmp(&b.end, buffer).is_lt() {
1916                a.end = b.end;
1917            }
1918            ranges.remove(ix + 1);
1919        } else {
1920            ix += 1;
1921        }
1922    }
1923}