inline_assistant.rs

   1use std::cmp;
   2use std::mem;
   3use std::ops::Range;
   4use std::rc::Rc;
   5use std::sync::Arc;
   6
   7use anyhow::{Context as _, Result};
   8use assistant_settings::AssistantSettings;
   9use client::telemetry::Telemetry;
  10use collections::{HashMap, HashSet, VecDeque, hash_map};
  11use editor::{
  12    Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorEvent, ExcerptId, ExcerptRange,
  13    GutterDimensions, MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint,
  14    actions::SelectAll,
  15    display_map::{
  16        BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock,
  17        ToDisplayPoint,
  18    },
  19};
  20use fs::Fs;
  21use gpui::{
  22    App, Context, Entity, Focusable, Global, HighlightStyle, Subscription, Task, UpdateGlobal,
  23    WeakEntity, Window, point,
  24};
  25use language::{Buffer, Point, Selection, TransactionId};
  26use language_model::ConfiguredModel;
  27use language_model::{LanguageModelRegistry, report_assistant_event};
  28use multi_buffer::MultiBufferRow;
  29use parking_lot::Mutex;
  30use project::LspAction;
  31use project::Project;
  32use project::{CodeAction, ProjectTransaction};
  33use prompt_store::PromptBuilder;
  34use prompt_store::PromptStore;
  35use settings::{Settings, SettingsStore};
  36use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
  37use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
  38use text::{OffsetRangeExt, ToPoint as _};
  39use ui::prelude::*;
  40use util::RangeExt;
  41use util::ResultExt;
  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 = AssistantSettings::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 = AssistantSettings::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 gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
 475            let prompt_editor = cx.new(|cx| {
 476                PromptEditor::new_buffer(
 477                    assist_id,
 478                    gutter_dimensions.clone(),
 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 gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
 594        let prompt_editor = cx.new(|cx| {
 595            PromptEditor::new_buffer(
 596                assist_id,
 597                gutter_dimensions.clone(),
 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            },
 667            BlockProperties {
 668                style: BlockStyle::Sticky,
 669                placement: BlockPlacement::Below(range.end),
 670                height: None,
 671                render: Arc::new(|cx| {
 672                    v_flex()
 673                        .h_full()
 674                        .w_full()
 675                        .border_t_1()
 676                        .border_color(cx.theme().status().info_border)
 677                        .into_any_element()
 678                }),
 679                priority: 0,
 680            },
 681        ];
 682
 683        editor.update(cx, |editor, cx| {
 684            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 685            [block_ids[0], block_ids[1]]
 686        })
 687    }
 688
 689    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 690        let assist = &self.assists[&assist_id];
 691        let Some(decorations) = assist.decorations.as_ref() else {
 692            return;
 693        };
 694        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 695        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 696
 697        assist_group.active_assist_id = Some(assist_id);
 698        if assist_group.linked {
 699            for assist_id in &assist_group.assist_ids {
 700                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 701                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 702                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 703                    });
 704                }
 705            }
 706        }
 707
 708        assist
 709            .editor
 710            .update(cx, |editor, cx| {
 711                let scroll_top = editor.scroll_position(cx).y;
 712                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 713                let prompt_row = editor
 714                    .row_for_block(decorations.prompt_block_id, cx)
 715                    .unwrap()
 716                    .0 as f32;
 717
 718                if (scroll_top..scroll_bottom).contains(&prompt_row) {
 719                    editor_assists.scroll_lock = Some(InlineAssistScrollLock {
 720                        assist_id,
 721                        distance_from_top: prompt_row - scroll_top,
 722                    });
 723                } else {
 724                    editor_assists.scroll_lock = None;
 725                }
 726            })
 727            .ok();
 728    }
 729
 730    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 731        let assist = &self.assists[&assist_id];
 732        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 733        if assist_group.active_assist_id == Some(assist_id) {
 734            assist_group.active_assist_id = None;
 735            if assist_group.linked {
 736                for assist_id in &assist_group.assist_ids {
 737                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 738                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 739                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 740                        });
 741                    }
 742                }
 743            }
 744        }
 745    }
 746
 747    fn handle_prompt_editor_event(
 748        &mut self,
 749        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 750        event: &PromptEditorEvent,
 751        window: &mut Window,
 752        cx: &mut App,
 753    ) {
 754        let assist_id = prompt_editor.read(cx).id();
 755        match event {
 756            PromptEditorEvent::StartRequested => {
 757                self.start_assist(assist_id, window, cx);
 758            }
 759            PromptEditorEvent::StopRequested => {
 760                self.stop_assist(assist_id, cx);
 761            }
 762            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 763                self.finish_assist(assist_id, false, window, cx);
 764            }
 765            PromptEditorEvent::CancelRequested => {
 766                self.finish_assist(assist_id, true, window, cx);
 767            }
 768            PromptEditorEvent::DismissRequested => {
 769                self.dismiss_assist(assist_id, window, cx);
 770            }
 771            PromptEditorEvent::Resized { .. } => {
 772                // This only matters for the terminal inline assistant
 773            }
 774        }
 775    }
 776
 777    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 778        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 779            return;
 780        };
 781
 782        if editor.read(cx).selections.count() == 1 {
 783            let (selection, buffer) = editor.update(cx, |editor, cx| {
 784                (
 785                    editor.selections.newest::<usize>(cx),
 786                    editor.buffer().read(cx).snapshot(cx),
 787                )
 788            });
 789            for assist_id in &editor_assists.assist_ids {
 790                let assist = &self.assists[assist_id];
 791                let assist_range = assist.range.to_offset(&buffer);
 792                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 793                {
 794                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 795                        self.dismiss_assist(*assist_id, window, cx);
 796                    } else {
 797                        self.finish_assist(*assist_id, false, window, cx);
 798                    }
 799
 800                    return;
 801                }
 802            }
 803        }
 804
 805        cx.propagate();
 806    }
 807
 808    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 809        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 810            return;
 811        };
 812
 813        if editor.read(cx).selections.count() == 1 {
 814            let (selection, buffer) = editor.update(cx, |editor, cx| {
 815                (
 816                    editor.selections.newest::<usize>(cx),
 817                    editor.buffer().read(cx).snapshot(cx),
 818                )
 819            });
 820            let mut closest_assist_fallback = None;
 821            for assist_id in &editor_assists.assist_ids {
 822                let assist = &self.assists[assist_id];
 823                let assist_range = assist.range.to_offset(&buffer);
 824                if assist.decorations.is_some() {
 825                    if assist_range.contains(&selection.start)
 826                        && assist_range.contains(&selection.end)
 827                    {
 828                        self.focus_assist(*assist_id, window, cx);
 829                        return;
 830                    } else {
 831                        let distance_from_selection = assist_range
 832                            .start
 833                            .abs_diff(selection.start)
 834                            .min(assist_range.start.abs_diff(selection.end))
 835                            + assist_range
 836                                .end
 837                                .abs_diff(selection.start)
 838                                .min(assist_range.end.abs_diff(selection.end));
 839                        match closest_assist_fallback {
 840                            Some((_, old_distance)) => {
 841                                if distance_from_selection < old_distance {
 842                                    closest_assist_fallback =
 843                                        Some((assist_id, distance_from_selection));
 844                                }
 845                            }
 846                            None => {
 847                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 848                            }
 849                        }
 850                    }
 851                }
 852            }
 853
 854            if let Some((&assist_id, _)) = closest_assist_fallback {
 855                self.focus_assist(assist_id, window, cx);
 856            }
 857        }
 858
 859        cx.propagate();
 860    }
 861
 862    fn handle_editor_release(
 863        &mut self,
 864        editor: WeakEntity<Editor>,
 865        window: &mut Window,
 866        cx: &mut App,
 867    ) {
 868        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 869            for assist_id in editor_assists.assist_ids.clone() {
 870                self.finish_assist(assist_id, true, window, cx);
 871            }
 872        }
 873    }
 874
 875    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 876        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 877            return;
 878        };
 879        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 880            return;
 881        };
 882        let assist = &self.assists[&scroll_lock.assist_id];
 883        let Some(decorations) = assist.decorations.as_ref() else {
 884            return;
 885        };
 886
 887        editor.update(cx, |editor, cx| {
 888            let scroll_position = editor.scroll_position(cx);
 889            let target_scroll_top = editor
 890                .row_for_block(decorations.prompt_block_id, cx)
 891                .unwrap()
 892                .0 as f32
 893                - scroll_lock.distance_from_top;
 894            if target_scroll_top != scroll_position.y {
 895                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 896            }
 897        });
 898    }
 899
 900    fn handle_editor_event(
 901        &mut self,
 902        editor: Entity<Editor>,
 903        event: &EditorEvent,
 904        window: &mut Window,
 905        cx: &mut App,
 906    ) {
 907        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 908            return;
 909        };
 910
 911        match event {
 912            EditorEvent::Edited { transaction_id } => {
 913                let buffer = editor.read(cx).buffer().read(cx);
 914                let edited_ranges =
 915                    buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
 916                let snapshot = buffer.snapshot(cx);
 917
 918                for assist_id in editor_assists.assist_ids.clone() {
 919                    let assist = &self.assists[&assist_id];
 920                    if matches!(
 921                        assist.codegen.read(cx).status(cx),
 922                        CodegenStatus::Error(_) | CodegenStatus::Done
 923                    ) {
 924                        let assist_range = assist.range.to_offset(&snapshot);
 925                        if edited_ranges
 926                            .iter()
 927                            .any(|range| range.overlaps(&assist_range))
 928                        {
 929                            self.finish_assist(assist_id, false, window, cx);
 930                        }
 931                    }
 932                }
 933            }
 934            EditorEvent::ScrollPositionChanged { .. } => {
 935                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 936                    let assist = &self.assists[&scroll_lock.assist_id];
 937                    if let Some(decorations) = assist.decorations.as_ref() {
 938                        let distance_from_top = editor.update(cx, |editor, cx| {
 939                            let scroll_top = editor.scroll_position(cx).y;
 940                            let prompt_row = editor
 941                                .row_for_block(decorations.prompt_block_id, cx)
 942                                .unwrap()
 943                                .0 as f32;
 944                            prompt_row - scroll_top
 945                        });
 946
 947                        if distance_from_top != scroll_lock.distance_from_top {
 948                            editor_assists.scroll_lock = None;
 949                        }
 950                    }
 951                }
 952            }
 953            EditorEvent::SelectionsChanged { .. } => {
 954                for assist_id in editor_assists.assist_ids.clone() {
 955                    let assist = &self.assists[&assist_id];
 956                    if let Some(decorations) = assist.decorations.as_ref() {
 957                        if decorations
 958                            .prompt_editor
 959                            .focus_handle(cx)
 960                            .is_focused(window)
 961                        {
 962                            return;
 963                        }
 964                    }
 965                }
 966
 967                editor_assists.scroll_lock = None;
 968            }
 969            _ => {}
 970        }
 971    }
 972
 973    pub fn finish_assist(
 974        &mut self,
 975        assist_id: InlineAssistId,
 976        undo: bool,
 977        window: &mut Window,
 978        cx: &mut App,
 979    ) {
 980        if let Some(assist) = self.assists.get(&assist_id) {
 981            let assist_group_id = assist.group_id;
 982            if self.assist_groups[&assist_group_id].linked {
 983                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
 984                    self.finish_assist(assist_id, undo, window, cx);
 985                }
 986                return;
 987            }
 988        }
 989
 990        self.dismiss_assist(assist_id, window, cx);
 991
 992        if let Some(assist) = self.assists.remove(&assist_id) {
 993            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
 994            {
 995                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 996                if entry.get().assist_ids.is_empty() {
 997                    entry.remove();
 998                }
 999            }
1000
1001            if let hash_map::Entry::Occupied(mut entry) =
1002                self.assists_by_editor.entry(assist.editor.clone())
1003            {
1004                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1005                if entry.get().assist_ids.is_empty() {
1006                    entry.remove();
1007                    if let Some(editor) = assist.editor.upgrade() {
1008                        self.update_editor_highlights(&editor, cx);
1009                    }
1010                } else {
1011                    entry.get().highlight_updates.send(()).ok();
1012                }
1013            }
1014
1015            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1016            let message_id = active_alternative.read(cx).message_id.clone();
1017
1018            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1019                let language_name = assist.editor.upgrade().and_then(|editor| {
1020                    let multibuffer = editor.read(cx).buffer().read(cx);
1021                    let snapshot = multibuffer.snapshot(cx);
1022                    let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
1023                    ranges
1024                        .first()
1025                        .and_then(|(buffer, _, _)| buffer.language())
1026                        .map(|language| language.name())
1027                });
1028                report_assistant_event(
1029                    AssistantEventData {
1030                        conversation_id: None,
1031                        kind: AssistantKind::Inline,
1032                        message_id,
1033                        phase: if undo {
1034                            AssistantPhase::Rejected
1035                        } else {
1036                            AssistantPhase::Accepted
1037                        },
1038                        model: model.model.telemetry_id(),
1039                        model_provider: model.model.provider_id().to_string(),
1040                        response_latency: None,
1041                        error_message: None,
1042                        language_name: language_name.map(|name| name.to_proto()),
1043                    },
1044                    Some(self.telemetry.clone()),
1045                    cx.http_client(),
1046                    model.model.api_key(cx),
1047                    cx.background_executor(),
1048                );
1049            }
1050
1051            if undo {
1052                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1053            } else {
1054                self.confirmed_assists.insert(assist_id, active_alternative);
1055            }
1056        }
1057    }
1058
1059    fn dismiss_assist(
1060        &mut self,
1061        assist_id: InlineAssistId,
1062        window: &mut Window,
1063        cx: &mut App,
1064    ) -> bool {
1065        let Some(assist) = self.assists.get_mut(&assist_id) else {
1066            return false;
1067        };
1068        let Some(editor) = assist.editor.upgrade() else {
1069            return false;
1070        };
1071        let Some(decorations) = assist.decorations.take() else {
1072            return false;
1073        };
1074
1075        editor.update(cx, |editor, cx| {
1076            let mut to_remove = decorations.removed_line_block_ids;
1077            to_remove.insert(decorations.prompt_block_id);
1078            to_remove.insert(decorations.end_block_id);
1079            editor.remove_blocks(to_remove, None, cx);
1080        });
1081
1082        if decorations
1083            .prompt_editor
1084            .focus_handle(cx)
1085            .contains_focused(window, cx)
1086        {
1087            self.focus_next_assist(assist_id, window, cx);
1088        }
1089
1090        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1091            if editor_assists
1092                .scroll_lock
1093                .as_ref()
1094                .map_or(false, |lock| lock.assist_id == assist_id)
1095            {
1096                editor_assists.scroll_lock = None;
1097            }
1098            editor_assists.highlight_updates.send(()).ok();
1099        }
1100
1101        true
1102    }
1103
1104    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1105        let Some(assist) = self.assists.get(&assist_id) else {
1106            return;
1107        };
1108
1109        let assist_group = &self.assist_groups[&assist.group_id];
1110        let assist_ix = assist_group
1111            .assist_ids
1112            .iter()
1113            .position(|id| *id == assist_id)
1114            .unwrap();
1115        let assist_ids = assist_group
1116            .assist_ids
1117            .iter()
1118            .skip(assist_ix + 1)
1119            .chain(assist_group.assist_ids.iter().take(assist_ix));
1120
1121        for assist_id in assist_ids {
1122            let assist = &self.assists[assist_id];
1123            if assist.decorations.is_some() {
1124                self.focus_assist(*assist_id, window, cx);
1125                return;
1126            }
1127        }
1128
1129        assist
1130            .editor
1131            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1132            .ok();
1133    }
1134
1135    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1136        let Some(assist) = self.assists.get(&assist_id) else {
1137            return;
1138        };
1139
1140        if let Some(decorations) = assist.decorations.as_ref() {
1141            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1142                prompt_editor.editor.update(cx, |editor, cx| {
1143                    window.focus(&editor.focus_handle(cx));
1144                    editor.select_all(&SelectAll, window, cx);
1145                })
1146            });
1147        }
1148
1149        self.scroll_to_assist(assist_id, window, cx);
1150    }
1151
1152    pub fn scroll_to_assist(
1153        &mut self,
1154        assist_id: InlineAssistId,
1155        window: &mut Window,
1156        cx: &mut App,
1157    ) {
1158        let Some(assist) = self.assists.get(&assist_id) else {
1159            return;
1160        };
1161        let Some(editor) = assist.editor.upgrade() else {
1162            return;
1163        };
1164
1165        let position = assist.range.start;
1166        editor.update(cx, |editor, cx| {
1167            editor.change_selections(None, window, cx, |selections| {
1168                selections.select_anchor_ranges([position..position])
1169            });
1170
1171            let mut scroll_target_top;
1172            let mut scroll_target_bottom;
1173            if let Some(decorations) = assist.decorations.as_ref() {
1174                scroll_target_top = editor
1175                    .row_for_block(decorations.prompt_block_id, cx)
1176                    .unwrap()
1177                    .0 as f32;
1178                scroll_target_bottom = editor
1179                    .row_for_block(decorations.end_block_id, cx)
1180                    .unwrap()
1181                    .0 as f32;
1182            } else {
1183                let snapshot = editor.snapshot(window, cx);
1184                let start_row = assist
1185                    .range
1186                    .start
1187                    .to_display_point(&snapshot.display_snapshot)
1188                    .row();
1189                scroll_target_top = start_row.0 as f32;
1190                scroll_target_bottom = scroll_target_top + 1.;
1191            }
1192            scroll_target_top -= editor.vertical_scroll_margin() as f32;
1193            scroll_target_bottom += editor.vertical_scroll_margin() as f32;
1194
1195            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1196            let scroll_top = editor.scroll_position(cx).y;
1197            let scroll_bottom = scroll_top + height_in_lines;
1198
1199            if scroll_target_top < scroll_top {
1200                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1201            } else if scroll_target_bottom > scroll_bottom {
1202                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1203                    editor.set_scroll_position(
1204                        point(0., scroll_target_bottom - height_in_lines),
1205                        window,
1206                        cx,
1207                    );
1208                } else {
1209                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1210                }
1211            }
1212        });
1213    }
1214
1215    fn unlink_assist_group(
1216        &mut self,
1217        assist_group_id: InlineAssistGroupId,
1218        window: &mut Window,
1219        cx: &mut App,
1220    ) -> Vec<InlineAssistId> {
1221        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1222        assist_group.linked = false;
1223
1224        for assist_id in &assist_group.assist_ids {
1225            let assist = self.assists.get_mut(assist_id).unwrap();
1226            if let Some(editor_decorations) = assist.decorations.as_ref() {
1227                editor_decorations
1228                    .prompt_editor
1229                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1230            }
1231        }
1232        assist_group.assist_ids.clone()
1233    }
1234
1235    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1236        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1237            assist
1238        } else {
1239            return;
1240        };
1241
1242        let assist_group_id = assist.group_id;
1243        if self.assist_groups[&assist_group_id].linked {
1244            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1245                self.start_assist(assist_id, window, cx);
1246            }
1247            return;
1248        }
1249
1250        let Some(user_prompt) = assist.user_prompt(cx) else {
1251            return;
1252        };
1253
1254        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1255        self.prompt_history.push_back(user_prompt.clone());
1256        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1257            self.prompt_history.pop_front();
1258        }
1259
1260        let Some(ConfiguredModel { model, .. }) =
1261            LanguageModelRegistry::read_global(cx).inline_assistant_model()
1262        else {
1263            return;
1264        };
1265
1266        assist
1267            .codegen
1268            .update(cx, |codegen, cx| codegen.start(model, user_prompt, cx))
1269            .log_err();
1270    }
1271
1272    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1273        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1274            assist
1275        } else {
1276            return;
1277        };
1278
1279        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1280    }
1281
1282    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1283        let mut gutter_pending_ranges = Vec::new();
1284        let mut gutter_transformed_ranges = Vec::new();
1285        let mut foreground_ranges = Vec::new();
1286        let mut inserted_row_ranges = Vec::new();
1287        let empty_assist_ids = Vec::new();
1288        let assist_ids = self
1289            .assists_by_editor
1290            .get(&editor.downgrade())
1291            .map_or(&empty_assist_ids, |editor_assists| {
1292                &editor_assists.assist_ids
1293            });
1294
1295        for assist_id in assist_ids {
1296            if let Some(assist) = self.assists.get(assist_id) {
1297                let codegen = assist.codegen.read(cx);
1298                let buffer = codegen.buffer(cx).read(cx).read(cx);
1299                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1300
1301                let pending_range =
1302                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1303                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1304                    gutter_pending_ranges.push(pending_range);
1305                }
1306
1307                if let Some(edit_position) = codegen.edit_position(cx) {
1308                    let edited_range = assist.range.start..edit_position;
1309                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1310                        gutter_transformed_ranges.push(edited_range);
1311                    }
1312                }
1313
1314                if assist.decorations.is_some() {
1315                    inserted_row_ranges
1316                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1317                }
1318            }
1319        }
1320
1321        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1322        merge_ranges(&mut foreground_ranges, &snapshot);
1323        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1324        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1325        editor.update(cx, |editor, cx| {
1326            enum GutterPendingRange {}
1327            if gutter_pending_ranges.is_empty() {
1328                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1329            } else {
1330                editor.highlight_gutter::<GutterPendingRange>(
1331                    &gutter_pending_ranges,
1332                    |cx| cx.theme().status().info_background,
1333                    cx,
1334                )
1335            }
1336
1337            enum GutterTransformedRange {}
1338            if gutter_transformed_ranges.is_empty() {
1339                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1340            } else {
1341                editor.highlight_gutter::<GutterTransformedRange>(
1342                    &gutter_transformed_ranges,
1343                    |cx| cx.theme().status().info,
1344                    cx,
1345                )
1346            }
1347
1348            if foreground_ranges.is_empty() {
1349                editor.clear_highlights::<InlineAssist>(cx);
1350            } else {
1351                editor.highlight_text::<InlineAssist>(
1352                    foreground_ranges,
1353                    HighlightStyle {
1354                        fade_out: Some(0.6),
1355                        ..Default::default()
1356                    },
1357                    cx,
1358                );
1359            }
1360
1361            editor.clear_row_highlights::<InlineAssist>();
1362            for row_range in inserted_row_ranges {
1363                editor.highlight_rows::<InlineAssist>(
1364                    row_range,
1365                    cx.theme().status().info_background,
1366                    Default::default(),
1367                    cx,
1368                );
1369            }
1370        });
1371    }
1372
1373    fn update_editor_blocks(
1374        &mut self,
1375        editor: &Entity<Editor>,
1376        assist_id: InlineAssistId,
1377        window: &mut Window,
1378        cx: &mut App,
1379    ) {
1380        let Some(assist) = self.assists.get_mut(&assist_id) else {
1381            return;
1382        };
1383        let Some(decorations) = assist.decorations.as_mut() else {
1384            return;
1385        };
1386
1387        let codegen = assist.codegen.read(cx);
1388        let old_snapshot = codegen.snapshot(cx);
1389        let old_buffer = codegen.old_buffer(cx);
1390        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1391
1392        editor.update(cx, |editor, cx| {
1393            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1394            editor.remove_blocks(old_blocks, None, cx);
1395
1396            let mut new_blocks = Vec::new();
1397            for (new_row, old_row_range) in deleted_row_ranges {
1398                let (_, buffer_start) = old_snapshot
1399                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1400                    .unwrap();
1401                let (_, buffer_end) = old_snapshot
1402                    .point_to_buffer_offset(Point::new(
1403                        *old_row_range.end(),
1404                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1405                    ))
1406                    .unwrap();
1407
1408                let deleted_lines_editor = cx.new(|cx| {
1409                    let multi_buffer =
1410                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1411                    multi_buffer.update(cx, |multi_buffer, cx| {
1412                        multi_buffer.push_excerpts(
1413                            old_buffer.clone(),
1414                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1415                            cx,
1416                        );
1417                    });
1418
1419                    enum DeletedLines {}
1420                    let mut editor = Editor::for_multibuffer(multi_buffer, None, 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_show_scrollbars(false, cx);
1426                    editor.set_read_only(true);
1427                    editor.set_show_edit_predictions(Some(false), window, cx);
1428                    editor.highlight_rows::<DeletedLines>(
1429                        Anchor::min()..Anchor::max(),
1430                        cx.theme().status().deleted_background,
1431                        Default::default(),
1432                        cx,
1433                    );
1434                    editor
1435                });
1436
1437                let height =
1438                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1439                new_blocks.push(BlockProperties {
1440                    placement: BlockPlacement::Above(new_row),
1441                    height: Some(height),
1442                    style: BlockStyle::Flex,
1443                    render: Arc::new(move |cx| {
1444                        div()
1445                            .block_mouse_down()
1446                            .bg(cx.theme().status().deleted_background)
1447                            .size_full()
1448                            .h(height as f32 * cx.window.line_height())
1449                            .pl(cx.gutter_dimensions.full_width())
1450                            .child(deleted_lines_editor.clone())
1451                            .into_any_element()
1452                    }),
1453                    priority: 0,
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: async_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) = async_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 gutter_dimensions = editor.read(cx).gutter_dimensions();
1612
1613        *gutter_dimensions.lock() = *cx.gutter_dimensions;
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(&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 !AssistantSettings::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}