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