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