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