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