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