inline_assistant.rs

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