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