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    #[allow(clippy::too_many_arguments)]
 480    pub fn suggest_assist(
 481        &mut self,
 482        editor: &Entity<Editor>,
 483        mut range: Range<Anchor>,
 484        initial_prompt: String,
 485        initial_transaction_id: Option<TransactionId>,
 486        focus: bool,
 487        workspace: WeakEntity<Workspace>,
 488        thread_store: Option<WeakEntity<ThreadStore>>,
 489        window: &mut Window,
 490        cx: &mut App,
 491    ) -> InlineAssistId {
 492        let assist_group_id = self.next_assist_group_id.post_inc();
 493        let prompt_buffer = cx.new(|cx| Buffer::local(&initial_prompt, cx));
 494        let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 495
 496        let assist_id = self.next_assist_id.post_inc();
 497
 498        let buffer = editor.read(cx).buffer().clone();
 499        {
 500            let snapshot = buffer.read(cx).read(cx);
 501            range.start = range.start.bias_left(&snapshot);
 502            range.end = range.end.bias_right(&snapshot);
 503        }
 504
 505        let context_store = cx.new(|_cx| ContextStore::new(workspace.clone()));
 506
 507        let codegen = cx.new(|cx| {
 508            BufferCodegen::new(
 509                editor.read(cx).buffer().clone(),
 510                range.clone(),
 511                initial_transaction_id,
 512                context_store.clone(),
 513                self.telemetry.clone(),
 514                self.prompt_builder.clone(),
 515                cx,
 516            )
 517        });
 518
 519        let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
 520        let prompt_editor = cx.new(|cx| {
 521            PromptEditor::new_buffer(
 522                assist_id,
 523                gutter_dimensions.clone(),
 524                self.prompt_history.clone(),
 525                prompt_buffer.clone(),
 526                codegen.clone(),
 527                self.fs.clone(),
 528                context_store,
 529                workspace.clone(),
 530                thread_store,
 531                window,
 532                cx,
 533            )
 534        });
 535
 536        let [prompt_block_id, end_block_id] =
 537            self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 538
 539        let editor_assists = self
 540            .assists_by_editor
 541            .entry(editor.downgrade())
 542            .or_insert_with(|| EditorInlineAssists::new(&editor, window, cx));
 543
 544        let mut assist_group = InlineAssistGroup::new();
 545        self.assists.insert(
 546            assist_id,
 547            InlineAssist::new(
 548                assist_id,
 549                assist_group_id,
 550                editor,
 551                &prompt_editor,
 552                prompt_block_id,
 553                end_block_id,
 554                range,
 555                codegen.clone(),
 556                workspace.clone(),
 557                window,
 558                cx,
 559            ),
 560        );
 561        assist_group.assist_ids.push(assist_id);
 562        editor_assists.assist_ids.push(assist_id);
 563        self.assist_groups.insert(assist_group_id, assist_group);
 564
 565        if focus {
 566            self.focus_assist(assist_id, window, cx);
 567        }
 568
 569        assist_id
 570    }
 571
 572    fn insert_assist_blocks(
 573        &self,
 574        editor: &Entity<Editor>,
 575        range: &Range<Anchor>,
 576        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
 577        cx: &mut App,
 578    ) -> [CustomBlockId; 2] {
 579        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 580            prompt_editor
 581                .editor
 582                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 583        });
 584        let assist_blocks = vec![
 585            BlockProperties {
 586                style: BlockStyle::Sticky,
 587                placement: BlockPlacement::Above(range.start),
 588                height: prompt_editor_height,
 589                render: build_assist_editor_renderer(prompt_editor),
 590                priority: 0,
 591            },
 592            BlockProperties {
 593                style: BlockStyle::Sticky,
 594                placement: BlockPlacement::Below(range.end),
 595                height: 0,
 596                render: Arc::new(|cx| {
 597                    v_flex()
 598                        .h_full()
 599                        .w_full()
 600                        .border_t_1()
 601                        .border_color(cx.theme().status().info_border)
 602                        .into_any_element()
 603                }),
 604                priority: 0,
 605            },
 606        ];
 607
 608        editor.update(cx, |editor, cx| {
 609            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 610            [block_ids[0], block_ids[1]]
 611        })
 612    }
 613
 614    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 615        let assist = &self.assists[&assist_id];
 616        let Some(decorations) = assist.decorations.as_ref() else {
 617            return;
 618        };
 619        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 620        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 621
 622        assist_group.active_assist_id = Some(assist_id);
 623        if assist_group.linked {
 624            for assist_id in &assist_group.assist_ids {
 625                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 626                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 627                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 628                    });
 629                }
 630            }
 631        }
 632
 633        assist
 634            .editor
 635            .update(cx, |editor, cx| {
 636                let scroll_top = editor.scroll_position(cx).y;
 637                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 638                let prompt_row = editor
 639                    .row_for_block(decorations.prompt_block_id, cx)
 640                    .unwrap()
 641                    .0 as f32;
 642
 643                if (scroll_top..scroll_bottom).contains(&prompt_row) {
 644                    editor_assists.scroll_lock = Some(InlineAssistScrollLock {
 645                        assist_id,
 646                        distance_from_top: prompt_row - scroll_top,
 647                    });
 648                } else {
 649                    editor_assists.scroll_lock = None;
 650                }
 651            })
 652            .ok();
 653    }
 654
 655    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 656        let assist = &self.assists[&assist_id];
 657        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 658        if assist_group.active_assist_id == Some(assist_id) {
 659            assist_group.active_assist_id = None;
 660            if assist_group.linked {
 661                for assist_id in &assist_group.assist_ids {
 662                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 663                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 664                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 665                        });
 666                    }
 667                }
 668            }
 669        }
 670    }
 671
 672    fn handle_prompt_editor_event(
 673        &mut self,
 674        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 675        event: &PromptEditorEvent,
 676        window: &mut Window,
 677        cx: &mut App,
 678    ) {
 679        let assist_id = prompt_editor.read(cx).id();
 680        match event {
 681            PromptEditorEvent::StartRequested => {
 682                self.start_assist(assist_id, window, cx);
 683            }
 684            PromptEditorEvent::StopRequested => {
 685                self.stop_assist(assist_id, cx);
 686            }
 687            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 688                self.finish_assist(assist_id, false, window, cx);
 689            }
 690            PromptEditorEvent::CancelRequested => {
 691                self.finish_assist(assist_id, true, window, cx);
 692            }
 693            PromptEditorEvent::DismissRequested => {
 694                self.dismiss_assist(assist_id, window, cx);
 695            }
 696            PromptEditorEvent::Resized { .. } => {
 697                // This only matters for the terminal inline assistant
 698            }
 699        }
 700    }
 701
 702    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 703        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 704            return;
 705        };
 706
 707        if editor.read(cx).selections.count() == 1 {
 708            let (selection, buffer) = editor.update(cx, |editor, cx| {
 709                (
 710                    editor.selections.newest::<usize>(cx),
 711                    editor.buffer().read(cx).snapshot(cx),
 712                )
 713            });
 714            for assist_id in &editor_assists.assist_ids {
 715                let assist = &self.assists[assist_id];
 716                let assist_range = assist.range.to_offset(&buffer);
 717                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 718                {
 719                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 720                        self.dismiss_assist(*assist_id, window, cx);
 721                    } else {
 722                        self.finish_assist(*assist_id, false, window, cx);
 723                    }
 724
 725                    return;
 726                }
 727            }
 728        }
 729
 730        cx.propagate();
 731    }
 732
 733    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 734        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 735            return;
 736        };
 737
 738        if editor.read(cx).selections.count() == 1 {
 739            let (selection, buffer) = editor.update(cx, |editor, cx| {
 740                (
 741                    editor.selections.newest::<usize>(cx),
 742                    editor.buffer().read(cx).snapshot(cx),
 743                )
 744            });
 745            let mut closest_assist_fallback = None;
 746            for assist_id in &editor_assists.assist_ids {
 747                let assist = &self.assists[assist_id];
 748                let assist_range = assist.range.to_offset(&buffer);
 749                if assist.decorations.is_some() {
 750                    if assist_range.contains(&selection.start)
 751                        && assist_range.contains(&selection.end)
 752                    {
 753                        self.focus_assist(*assist_id, window, cx);
 754                        return;
 755                    } else {
 756                        let distance_from_selection = assist_range
 757                            .start
 758                            .abs_diff(selection.start)
 759                            .min(assist_range.start.abs_diff(selection.end))
 760                            + assist_range
 761                                .end
 762                                .abs_diff(selection.start)
 763                                .min(assist_range.end.abs_diff(selection.end));
 764                        match closest_assist_fallback {
 765                            Some((_, old_distance)) => {
 766                                if distance_from_selection < old_distance {
 767                                    closest_assist_fallback =
 768                                        Some((assist_id, distance_from_selection));
 769                                }
 770                            }
 771                            None => {
 772                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 773                            }
 774                        }
 775                    }
 776                }
 777            }
 778
 779            if let Some((&assist_id, _)) = closest_assist_fallback {
 780                self.focus_assist(assist_id, window, cx);
 781            }
 782        }
 783
 784        cx.propagate();
 785    }
 786
 787    fn handle_editor_release(
 788        &mut self,
 789        editor: WeakEntity<Editor>,
 790        window: &mut Window,
 791        cx: &mut App,
 792    ) {
 793        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 794            for assist_id in editor_assists.assist_ids.clone() {
 795                self.finish_assist(assist_id, true, window, cx);
 796            }
 797        }
 798    }
 799
 800    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 801        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 802            return;
 803        };
 804        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 805            return;
 806        };
 807        let assist = &self.assists[&scroll_lock.assist_id];
 808        let Some(decorations) = assist.decorations.as_ref() else {
 809            return;
 810        };
 811
 812        editor.update(cx, |editor, cx| {
 813            let scroll_position = editor.scroll_position(cx);
 814            let target_scroll_top = editor
 815                .row_for_block(decorations.prompt_block_id, cx)
 816                .unwrap()
 817                .0 as f32
 818                - scroll_lock.distance_from_top;
 819            if target_scroll_top != scroll_position.y {
 820                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 821            }
 822        });
 823    }
 824
 825    fn handle_editor_event(
 826        &mut self,
 827        editor: Entity<Editor>,
 828        event: &EditorEvent,
 829        window: &mut Window,
 830        cx: &mut App,
 831    ) {
 832        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 833            return;
 834        };
 835
 836        match event {
 837            EditorEvent::Edited { transaction_id } => {
 838                let buffer = editor.read(cx).buffer().read(cx);
 839                let edited_ranges =
 840                    buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
 841                let snapshot = buffer.snapshot(cx);
 842
 843                for assist_id in editor_assists.assist_ids.clone() {
 844                    let assist = &self.assists[&assist_id];
 845                    if matches!(
 846                        assist.codegen.read(cx).status(cx),
 847                        CodegenStatus::Error(_) | CodegenStatus::Done
 848                    ) {
 849                        let assist_range = assist.range.to_offset(&snapshot);
 850                        if edited_ranges
 851                            .iter()
 852                            .any(|range| range.overlaps(&assist_range))
 853                        {
 854                            self.finish_assist(assist_id, false, window, cx);
 855                        }
 856                    }
 857                }
 858            }
 859            EditorEvent::ScrollPositionChanged { .. } => {
 860                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 861                    let assist = &self.assists[&scroll_lock.assist_id];
 862                    if let Some(decorations) = assist.decorations.as_ref() {
 863                        let distance_from_top = editor.update(cx, |editor, cx| {
 864                            let scroll_top = editor.scroll_position(cx).y;
 865                            let prompt_row = editor
 866                                .row_for_block(decorations.prompt_block_id, cx)
 867                                .unwrap()
 868                                .0 as f32;
 869                            prompt_row - scroll_top
 870                        });
 871
 872                        if distance_from_top != scroll_lock.distance_from_top {
 873                            editor_assists.scroll_lock = None;
 874                        }
 875                    }
 876                }
 877            }
 878            EditorEvent::SelectionsChanged { .. } => {
 879                for assist_id in editor_assists.assist_ids.clone() {
 880                    let assist = &self.assists[&assist_id];
 881                    if let Some(decorations) = assist.decorations.as_ref() {
 882                        if decorations
 883                            .prompt_editor
 884                            .focus_handle(cx)
 885                            .is_focused(window)
 886                        {
 887                            return;
 888                        }
 889                    }
 890                }
 891
 892                editor_assists.scroll_lock = None;
 893            }
 894            _ => {}
 895        }
 896    }
 897
 898    pub fn finish_assist(
 899        &mut self,
 900        assist_id: InlineAssistId,
 901        undo: bool,
 902        window: &mut Window,
 903        cx: &mut App,
 904    ) {
 905        if let Some(assist) = self.assists.get(&assist_id) {
 906            let assist_group_id = assist.group_id;
 907            if self.assist_groups[&assist_group_id].linked {
 908                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
 909                    self.finish_assist(assist_id, undo, window, cx);
 910                }
 911                return;
 912            }
 913        }
 914
 915        self.dismiss_assist(assist_id, window, cx);
 916
 917        if let Some(assist) = self.assists.remove(&assist_id) {
 918            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
 919            {
 920                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 921                if entry.get().assist_ids.is_empty() {
 922                    entry.remove();
 923                }
 924            }
 925
 926            if let hash_map::Entry::Occupied(mut entry) =
 927                self.assists_by_editor.entry(assist.editor.clone())
 928            {
 929                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 930                if entry.get().assist_ids.is_empty() {
 931                    entry.remove();
 932                    if let Some(editor) = assist.editor.upgrade() {
 933                        self.update_editor_highlights(&editor, cx);
 934                    }
 935                } else {
 936                    entry.get().highlight_updates.send(()).ok();
 937                }
 938            }
 939
 940            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
 941            let message_id = active_alternative.read(cx).message_id.clone();
 942
 943            if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
 944                let language_name = assist.editor.upgrade().and_then(|editor| {
 945                    let multibuffer = editor.read(cx).buffer().read(cx);
 946                    let snapshot = multibuffer.snapshot(cx);
 947                    let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
 948                    ranges
 949                        .first()
 950                        .and_then(|(buffer, _, _)| buffer.language())
 951                        .map(|language| language.name())
 952                });
 953                report_assistant_event(
 954                    AssistantEvent {
 955                        conversation_id: None,
 956                        kind: AssistantKind::Inline,
 957                        message_id,
 958                        phase: if undo {
 959                            AssistantPhase::Rejected
 960                        } else {
 961                            AssistantPhase::Accepted
 962                        },
 963                        model: model.telemetry_id(),
 964                        model_provider: model.provider_id().to_string(),
 965                        response_latency: None,
 966                        error_message: None,
 967                        language_name: language_name.map(|name| name.to_proto()),
 968                    },
 969                    Some(self.telemetry.clone()),
 970                    cx.http_client(),
 971                    model.api_key(cx),
 972                    cx.background_executor(),
 973                );
 974            }
 975
 976            if undo {
 977                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
 978            } else {
 979                self.confirmed_assists.insert(assist_id, active_alternative);
 980            }
 981        }
 982    }
 983
 984    fn dismiss_assist(
 985        &mut self,
 986        assist_id: InlineAssistId,
 987        window: &mut Window,
 988        cx: &mut App,
 989    ) -> bool {
 990        let Some(assist) = self.assists.get_mut(&assist_id) else {
 991            return false;
 992        };
 993        let Some(editor) = assist.editor.upgrade() else {
 994            return false;
 995        };
 996        let Some(decorations) = assist.decorations.take() else {
 997            return false;
 998        };
 999
1000        editor.update(cx, |editor, cx| {
1001            let mut to_remove = decorations.removed_line_block_ids;
1002            to_remove.insert(decorations.prompt_block_id);
1003            to_remove.insert(decorations.end_block_id);
1004            editor.remove_blocks(to_remove, None, cx);
1005        });
1006
1007        if decorations
1008            .prompt_editor
1009            .focus_handle(cx)
1010            .contains_focused(window, cx)
1011        {
1012            self.focus_next_assist(assist_id, window, cx);
1013        }
1014
1015        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1016            if editor_assists
1017                .scroll_lock
1018                .as_ref()
1019                .map_or(false, |lock| lock.assist_id == assist_id)
1020            {
1021                editor_assists.scroll_lock = None;
1022            }
1023            editor_assists.highlight_updates.send(()).ok();
1024        }
1025
1026        true
1027    }
1028
1029    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1030        let Some(assist) = self.assists.get(&assist_id) else {
1031            return;
1032        };
1033
1034        let assist_group = &self.assist_groups[&assist.group_id];
1035        let assist_ix = assist_group
1036            .assist_ids
1037            .iter()
1038            .position(|id| *id == assist_id)
1039            .unwrap();
1040        let assist_ids = assist_group
1041            .assist_ids
1042            .iter()
1043            .skip(assist_ix + 1)
1044            .chain(assist_group.assist_ids.iter().take(assist_ix));
1045
1046        for assist_id in assist_ids {
1047            let assist = &self.assists[assist_id];
1048            if assist.decorations.is_some() {
1049                self.focus_assist(*assist_id, window, cx);
1050                return;
1051            }
1052        }
1053
1054        assist
1055            .editor
1056            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1057            .ok();
1058    }
1059
1060    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1061        let Some(assist) = self.assists.get(&assist_id) else {
1062            return;
1063        };
1064
1065        if let Some(decorations) = assist.decorations.as_ref() {
1066            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1067                prompt_editor.editor.update(cx, |editor, cx| {
1068                    window.focus(&editor.focus_handle(cx));
1069                    editor.select_all(&SelectAll, window, cx);
1070                })
1071            });
1072        }
1073
1074        self.scroll_to_assist(assist_id, window, cx);
1075    }
1076
1077    pub fn scroll_to_assist(
1078        &mut self,
1079        assist_id: InlineAssistId,
1080        window: &mut Window,
1081        cx: &mut App,
1082    ) {
1083        let Some(assist) = self.assists.get(&assist_id) else {
1084            return;
1085        };
1086        let Some(editor) = assist.editor.upgrade() else {
1087            return;
1088        };
1089
1090        let position = assist.range.start;
1091        editor.update(cx, |editor, cx| {
1092            editor.change_selections(None, window, cx, |selections| {
1093                selections.select_anchor_ranges([position..position])
1094            });
1095
1096            let mut scroll_target_top;
1097            let mut scroll_target_bottom;
1098            if let Some(decorations) = assist.decorations.as_ref() {
1099                scroll_target_top = editor
1100                    .row_for_block(decorations.prompt_block_id, cx)
1101                    .unwrap()
1102                    .0 as f32;
1103                scroll_target_bottom = editor
1104                    .row_for_block(decorations.end_block_id, cx)
1105                    .unwrap()
1106                    .0 as f32;
1107            } else {
1108                let snapshot = editor.snapshot(window, cx);
1109                let start_row = assist
1110                    .range
1111                    .start
1112                    .to_display_point(&snapshot.display_snapshot)
1113                    .row();
1114                scroll_target_top = start_row.0 as f32;
1115                scroll_target_bottom = scroll_target_top + 1.;
1116            }
1117            scroll_target_top -= editor.vertical_scroll_margin() as f32;
1118            scroll_target_bottom += editor.vertical_scroll_margin() as f32;
1119
1120            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1121            let scroll_top = editor.scroll_position(cx).y;
1122            let scroll_bottom = scroll_top + height_in_lines;
1123
1124            if scroll_target_top < scroll_top {
1125                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1126            } else if scroll_target_bottom > scroll_bottom {
1127                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1128                    editor.set_scroll_position(
1129                        point(0., scroll_target_bottom - height_in_lines),
1130                        window,
1131                        cx,
1132                    );
1133                } else {
1134                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1135                }
1136            }
1137        });
1138    }
1139
1140    fn unlink_assist_group(
1141        &mut self,
1142        assist_group_id: InlineAssistGroupId,
1143        window: &mut Window,
1144        cx: &mut App,
1145    ) -> Vec<InlineAssistId> {
1146        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1147        assist_group.linked = false;
1148        for assist_id in &assist_group.assist_ids {
1149            let assist = self.assists.get_mut(assist_id).unwrap();
1150            if let Some(editor_decorations) = assist.decorations.as_ref() {
1151                editor_decorations
1152                    .prompt_editor
1153                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1154            }
1155        }
1156        assist_group.assist_ids.clone()
1157    }
1158
1159    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1160        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1161            assist
1162        } else {
1163            return;
1164        };
1165
1166        let assist_group_id = assist.group_id;
1167        if self.assist_groups[&assist_group_id].linked {
1168            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1169                self.start_assist(assist_id, window, cx);
1170            }
1171            return;
1172        }
1173
1174        let Some(user_prompt) = assist.user_prompt(cx) else {
1175            return;
1176        };
1177
1178        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1179        self.prompt_history.push_back(user_prompt.clone());
1180        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1181            self.prompt_history.pop_front();
1182        }
1183
1184        assist
1185            .codegen
1186            .update(cx, |codegen, cx| codegen.start(user_prompt, cx))
1187            .log_err();
1188    }
1189
1190    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1191        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1192            assist
1193        } else {
1194            return;
1195        };
1196
1197        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1198    }
1199
1200    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1201        let mut gutter_pending_ranges = Vec::new();
1202        let mut gutter_transformed_ranges = Vec::new();
1203        let mut foreground_ranges = Vec::new();
1204        let mut inserted_row_ranges = Vec::new();
1205        let empty_assist_ids = Vec::new();
1206        let assist_ids = self
1207            .assists_by_editor
1208            .get(&editor.downgrade())
1209            .map_or(&empty_assist_ids, |editor_assists| {
1210                &editor_assists.assist_ids
1211            });
1212
1213        for assist_id in assist_ids {
1214            if let Some(assist) = self.assists.get(assist_id) {
1215                let codegen = assist.codegen.read(cx);
1216                let buffer = codegen.buffer(cx).read(cx).read(cx);
1217                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1218
1219                let pending_range =
1220                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1221                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1222                    gutter_pending_ranges.push(pending_range);
1223                }
1224
1225                if let Some(edit_position) = codegen.edit_position(cx) {
1226                    let edited_range = assist.range.start..edit_position;
1227                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1228                        gutter_transformed_ranges.push(edited_range);
1229                    }
1230                }
1231
1232                if assist.decorations.is_some() {
1233                    inserted_row_ranges
1234                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1235                }
1236            }
1237        }
1238
1239        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1240        merge_ranges(&mut foreground_ranges, &snapshot);
1241        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1242        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1243        editor.update(cx, |editor, cx| {
1244            enum GutterPendingRange {}
1245            if gutter_pending_ranges.is_empty() {
1246                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1247            } else {
1248                editor.highlight_gutter::<GutterPendingRange>(
1249                    &gutter_pending_ranges,
1250                    |cx| cx.theme().status().info_background,
1251                    cx,
1252                )
1253            }
1254
1255            enum GutterTransformedRange {}
1256            if gutter_transformed_ranges.is_empty() {
1257                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1258            } else {
1259                editor.highlight_gutter::<GutterTransformedRange>(
1260                    &gutter_transformed_ranges,
1261                    |cx| cx.theme().status().info,
1262                    cx,
1263                )
1264            }
1265
1266            if foreground_ranges.is_empty() {
1267                editor.clear_highlights::<InlineAssist>(cx);
1268            } else {
1269                editor.highlight_text::<InlineAssist>(
1270                    foreground_ranges,
1271                    HighlightStyle {
1272                        fade_out: Some(0.6),
1273                        ..Default::default()
1274                    },
1275                    cx,
1276                );
1277            }
1278
1279            editor.clear_row_highlights::<InlineAssist>();
1280            for row_range in inserted_row_ranges {
1281                editor.highlight_rows::<InlineAssist>(
1282                    row_range,
1283                    cx.theme().status().info_background,
1284                    false,
1285                    cx,
1286                );
1287            }
1288        });
1289    }
1290
1291    fn update_editor_blocks(
1292        &mut self,
1293        editor: &Entity<Editor>,
1294        assist_id: InlineAssistId,
1295        window: &mut Window,
1296        cx: &mut App,
1297    ) {
1298        let Some(assist) = self.assists.get_mut(&assist_id) else {
1299            return;
1300        };
1301        let Some(decorations) = assist.decorations.as_mut() else {
1302            return;
1303        };
1304
1305        let codegen = assist.codegen.read(cx);
1306        let old_snapshot = codegen.snapshot(cx);
1307        let old_buffer = codegen.old_buffer(cx);
1308        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1309
1310        editor.update(cx, |editor, cx| {
1311            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1312            editor.remove_blocks(old_blocks, None, cx);
1313
1314            let mut new_blocks = Vec::new();
1315            for (new_row, old_row_range) in deleted_row_ranges {
1316                let (_, buffer_start) = old_snapshot
1317                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1318                    .unwrap();
1319                let (_, buffer_end) = old_snapshot
1320                    .point_to_buffer_offset(Point::new(
1321                        *old_row_range.end(),
1322                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1323                    ))
1324                    .unwrap();
1325
1326                let deleted_lines_editor = cx.new(|cx| {
1327                    let multi_buffer =
1328                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1329                    multi_buffer.update(cx, |multi_buffer, cx| {
1330                        multi_buffer.push_excerpts(
1331                            old_buffer.clone(),
1332                            Some(ExcerptRange {
1333                                context: buffer_start..buffer_end,
1334                                primary: None,
1335                            }),
1336                            cx,
1337                        );
1338                    });
1339
1340                    enum DeletedLines {}
1341                    let mut editor = Editor::for_multibuffer(multi_buffer, None, true, window, cx);
1342                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1343                    editor.set_show_wrap_guides(false, cx);
1344                    editor.set_show_gutter(false, cx);
1345                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1346                    editor.set_show_scrollbars(false, cx);
1347                    editor.set_read_only(true);
1348                    editor.set_show_edit_predictions(Some(false), window, cx);
1349                    editor.highlight_rows::<DeletedLines>(
1350                        Anchor::min()..Anchor::max(),
1351                        cx.theme().status().deleted_background,
1352                        false,
1353                        cx,
1354                    );
1355                    editor
1356                });
1357
1358                let height =
1359                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1360                new_blocks.push(BlockProperties {
1361                    placement: BlockPlacement::Above(new_row),
1362                    height,
1363                    style: BlockStyle::Flex,
1364                    render: Arc::new(move |cx| {
1365                        div()
1366                            .block_mouse_down()
1367                            .bg(cx.theme().status().deleted_background)
1368                            .size_full()
1369                            .h(height as f32 * cx.window.line_height())
1370                            .pl(cx.gutter_dimensions.full_width())
1371                            .child(deleted_lines_editor.clone())
1372                            .into_any_element()
1373                    }),
1374                    priority: 0,
1375                });
1376            }
1377
1378            decorations.removed_line_block_ids = editor
1379                .insert_blocks(new_blocks, None, cx)
1380                .into_iter()
1381                .collect();
1382        })
1383    }
1384
1385    fn resolve_inline_assist_target(
1386        workspace: &mut Workspace,
1387        window: &mut Window,
1388        cx: &mut App,
1389    ) -> Option<InlineAssistTarget> {
1390        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
1391            if terminal_panel
1392                .read(cx)
1393                .focus_handle(cx)
1394                .contains_focused(window, cx)
1395            {
1396                if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1397                    pane.read(cx)
1398                        .active_item()
1399                        .and_then(|t| t.downcast::<TerminalView>())
1400                }) {
1401                    return Some(InlineAssistTarget::Terminal(terminal_view));
1402                }
1403            }
1404        }
1405
1406        if let Some(workspace_editor) = workspace
1407            .active_item(cx)
1408            .and_then(|item| item.act_as::<Editor>(cx))
1409        {
1410            Some(InlineAssistTarget::Editor(workspace_editor))
1411        } else if let Some(terminal_view) = workspace
1412            .active_item(cx)
1413            .and_then(|item| item.act_as::<TerminalView>(cx))
1414        {
1415            Some(InlineAssistTarget::Terminal(terminal_view))
1416        } else {
1417            None
1418        }
1419    }
1420}
1421
1422struct EditorInlineAssists {
1423    assist_ids: Vec<InlineAssistId>,
1424    scroll_lock: Option<InlineAssistScrollLock>,
1425    highlight_updates: async_watch::Sender<()>,
1426    _update_highlights: Task<Result<()>>,
1427    _subscriptions: Vec<gpui::Subscription>,
1428}
1429
1430struct InlineAssistScrollLock {
1431    assist_id: InlineAssistId,
1432    distance_from_top: f32,
1433}
1434
1435impl EditorInlineAssists {
1436    #[allow(clippy::too_many_arguments)]
1437    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1438        let (highlight_updates_tx, mut highlight_updates_rx) = async_watch::channel(());
1439        Self {
1440            assist_ids: Vec::new(),
1441            scroll_lock: None,
1442            highlight_updates: highlight_updates_tx,
1443            _update_highlights: cx.spawn(|cx| {
1444                let editor = editor.downgrade();
1445                async move {
1446                    while let Ok(()) = highlight_updates_rx.changed().await {
1447                        let editor = editor.upgrade().context("editor was dropped")?;
1448                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1449                            assistant.update_editor_highlights(&editor, cx);
1450                        })?;
1451                    }
1452                    Ok(())
1453                }
1454            }),
1455            _subscriptions: vec![
1456                cx.observe_release_in(editor, window, {
1457                    let editor = editor.downgrade();
1458                    |_, window, cx| {
1459                        InlineAssistant::update_global(cx, |this, cx| {
1460                            this.handle_editor_release(editor, window, cx);
1461                        })
1462                    }
1463                }),
1464                window.observe(editor, cx, move |editor, window, cx| {
1465                    InlineAssistant::update_global(cx, |this, cx| {
1466                        this.handle_editor_change(editor, window, cx)
1467                    })
1468                }),
1469                window.subscribe(editor, cx, move |editor, event, window, cx| {
1470                    InlineAssistant::update_global(cx, |this, cx| {
1471                        this.handle_editor_event(editor, event, window, cx)
1472                    })
1473                }),
1474                editor.update(cx, |editor, cx| {
1475                    let editor_handle = cx.entity().downgrade();
1476                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1477                        InlineAssistant::update_global(cx, |this, cx| {
1478                            if let Some(editor) = editor_handle.upgrade() {
1479                                this.handle_editor_newline(editor, window, cx)
1480                            }
1481                        })
1482                    })
1483                }),
1484                editor.update(cx, |editor, cx| {
1485                    let editor_handle = cx.entity().downgrade();
1486                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1487                        InlineAssistant::update_global(cx, |this, cx| {
1488                            if let Some(editor) = editor_handle.upgrade() {
1489                                this.handle_editor_cancel(editor, window, cx)
1490                            }
1491                        })
1492                    })
1493                }),
1494            ],
1495        }
1496    }
1497}
1498
1499struct InlineAssistGroup {
1500    assist_ids: Vec<InlineAssistId>,
1501    linked: bool,
1502    active_assist_id: Option<InlineAssistId>,
1503}
1504
1505impl InlineAssistGroup {
1506    fn new() -> Self {
1507        Self {
1508            assist_ids: Vec::new(),
1509            linked: true,
1510            active_assist_id: None,
1511        }
1512    }
1513}
1514
1515fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1516    let editor = editor.clone();
1517
1518    Arc::new(move |cx: &mut BlockContext| {
1519        let gutter_dimensions = editor.read(cx).gutter_dimensions();
1520
1521        *gutter_dimensions.lock() = *cx.gutter_dimensions;
1522        editor.clone().into_any_element()
1523    })
1524}
1525
1526#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1527struct InlineAssistGroupId(usize);
1528
1529impl InlineAssistGroupId {
1530    fn post_inc(&mut self) -> InlineAssistGroupId {
1531        let id = *self;
1532        self.0 += 1;
1533        id
1534    }
1535}
1536
1537pub struct InlineAssist {
1538    group_id: InlineAssistGroupId,
1539    range: Range<Anchor>,
1540    editor: WeakEntity<Editor>,
1541    decorations: Option<InlineAssistDecorations>,
1542    codegen: Entity<BufferCodegen>,
1543    _subscriptions: Vec<Subscription>,
1544    workspace: WeakEntity<Workspace>,
1545}
1546
1547impl InlineAssist {
1548    #[allow(clippy::too_many_arguments)]
1549    fn new(
1550        assist_id: InlineAssistId,
1551        group_id: InlineAssistGroupId,
1552        editor: &Entity<Editor>,
1553        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1554        prompt_block_id: CustomBlockId,
1555        end_block_id: CustomBlockId,
1556        range: Range<Anchor>,
1557        codegen: Entity<BufferCodegen>,
1558        workspace: WeakEntity<Workspace>,
1559        window: &mut Window,
1560        cx: &mut App,
1561    ) -> Self {
1562        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1563        InlineAssist {
1564            group_id,
1565            editor: editor.downgrade(),
1566            decorations: Some(InlineAssistDecorations {
1567                prompt_block_id,
1568                prompt_editor: prompt_editor.clone(),
1569                removed_line_block_ids: HashSet::default(),
1570                end_block_id,
1571            }),
1572            range,
1573            codegen: codegen.clone(),
1574            workspace: workspace.clone(),
1575            _subscriptions: vec![
1576                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1577                    InlineAssistant::update_global(cx, |this, cx| {
1578                        this.handle_prompt_editor_focus_in(assist_id, cx)
1579                    })
1580                }),
1581                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1582                    InlineAssistant::update_global(cx, |this, cx| {
1583                        this.handle_prompt_editor_focus_out(assist_id, cx)
1584                    })
1585                }),
1586                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1587                    InlineAssistant::update_global(cx, |this, cx| {
1588                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1589                    })
1590                }),
1591                window.observe(&codegen, cx, {
1592                    let editor = editor.downgrade();
1593                    move |_, window, cx| {
1594                        if let Some(editor) = editor.upgrade() {
1595                            InlineAssistant::update_global(cx, |this, cx| {
1596                                if let Some(editor_assists) =
1597                                    this.assists_by_editor.get(&editor.downgrade())
1598                                {
1599                                    editor_assists.highlight_updates.send(()).ok();
1600                                }
1601
1602                                this.update_editor_blocks(&editor, assist_id, window, cx);
1603                            })
1604                        }
1605                    }
1606                }),
1607                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1608                    InlineAssistant::update_global(cx, |this, cx| match event {
1609                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1610                        CodegenEvent::Finished => {
1611                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1612                                assist
1613                            } else {
1614                                return;
1615                            };
1616
1617                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx) {
1618                                if assist.decorations.is_none() {
1619                                    if let Some(workspace) = assist.workspace.upgrade() {
1620                                        let error = format!("Inline assistant error: {}", error);
1621                                        workspace.update(cx, |workspace, cx| {
1622                                            struct InlineAssistantError;
1623
1624                                            let id =
1625                                                NotificationId::composite::<InlineAssistantError>(
1626                                                    assist_id.0,
1627                                                );
1628
1629                                            workspace.show_toast(Toast::new(id, error), cx);
1630                                        })
1631                                    }
1632                                }
1633                            }
1634
1635                            if assist.decorations.is_none() {
1636                                this.finish_assist(assist_id, false, window, cx);
1637                            }
1638                        }
1639                    })
1640                }),
1641            ],
1642        }
1643    }
1644
1645    fn user_prompt(&self, cx: &App) -> Option<String> {
1646        let decorations = self.decorations.as_ref()?;
1647        Some(decorations.prompt_editor.read(cx).prompt(cx))
1648    }
1649}
1650
1651struct InlineAssistDecorations {
1652    prompt_block_id: CustomBlockId,
1653    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1654    removed_line_block_ids: HashSet<CustomBlockId>,
1655    end_block_id: CustomBlockId,
1656}
1657
1658struct AssistantCodeActionProvider {
1659    editor: WeakEntity<Editor>,
1660    workspace: WeakEntity<Workspace>,
1661    thread_store: Option<WeakEntity<ThreadStore>>,
1662}
1663
1664const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant2";
1665
1666impl CodeActionProvider for AssistantCodeActionProvider {
1667    fn id(&self) -> Arc<str> {
1668        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1669    }
1670
1671    fn code_actions(
1672        &self,
1673        buffer: &Entity<Buffer>,
1674        range: Range<text::Anchor>,
1675        _: &mut Window,
1676        cx: &mut App,
1677    ) -> Task<Result<Vec<CodeAction>>> {
1678        if !AssistantSettings::get_global(cx).enabled {
1679            return Task::ready(Ok(Vec::new()));
1680        }
1681
1682        let snapshot = buffer.read(cx).snapshot();
1683        let mut range = range.to_point(&snapshot);
1684
1685        // Expand the range to line boundaries.
1686        range.start.column = 0;
1687        range.end.column = snapshot.line_len(range.end.row);
1688
1689        let mut has_diagnostics = false;
1690        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1691            range.start = cmp::min(range.start, diagnostic.range.start);
1692            range.end = cmp::max(range.end, diagnostic.range.end);
1693            has_diagnostics = true;
1694        }
1695        if has_diagnostics {
1696            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
1697                if let Some(symbol) = symbols_containing_start.last() {
1698                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1699                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1700                }
1701            }
1702
1703            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
1704                if let Some(symbol) = symbols_containing_end.last() {
1705                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1706                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1707                }
1708            }
1709
1710            Task::ready(Ok(vec![CodeAction {
1711                server_id: language::LanguageServerId(0),
1712                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1713                lsp_action: lsp::CodeAction {
1714                    title: "Fix with Assistant".into(),
1715                    ..Default::default()
1716                },
1717            }]))
1718        } else {
1719            Task::ready(Ok(Vec::new()))
1720        }
1721    }
1722
1723    fn apply_code_action(
1724        &self,
1725        buffer: Entity<Buffer>,
1726        action: CodeAction,
1727        excerpt_id: ExcerptId,
1728        _push_to_history: bool,
1729        window: &mut Window,
1730        cx: &mut App,
1731    ) -> Task<Result<ProjectTransaction>> {
1732        let editor = self.editor.clone();
1733        let workspace = self.workspace.clone();
1734        let thread_store = self.thread_store.clone();
1735        window.spawn(cx, |mut cx| async move {
1736            let editor = editor.upgrade().context("editor was released")?;
1737            let range = editor
1738                .update(&mut cx, |editor, cx| {
1739                    editor.buffer().update(cx, |multibuffer, cx| {
1740                        let buffer = buffer.read(cx);
1741                        let multibuffer_snapshot = multibuffer.read(cx);
1742
1743                        let old_context_range =
1744                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1745                        let mut new_context_range = old_context_range.clone();
1746                        if action
1747                            .range
1748                            .start
1749                            .cmp(&old_context_range.start, buffer)
1750                            .is_lt()
1751                        {
1752                            new_context_range.start = action.range.start;
1753                        }
1754                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1755                            new_context_range.end = action.range.end;
1756                        }
1757                        drop(multibuffer_snapshot);
1758
1759                        if new_context_range != old_context_range {
1760                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1761                        }
1762
1763                        let multibuffer_snapshot = multibuffer.read(cx);
1764                        Some(
1765                            multibuffer_snapshot
1766                                .anchor_in_excerpt(excerpt_id, action.range.start)?
1767                                ..multibuffer_snapshot
1768                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
1769                        )
1770                    })
1771                })?
1772                .context("invalid range")?;
1773
1774            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1775                let assist_id = assistant.suggest_assist(
1776                    &editor,
1777                    range,
1778                    "Fix Diagnostics".into(),
1779                    None,
1780                    true,
1781                    workspace,
1782                    thread_store,
1783                    window,
1784                    cx,
1785                );
1786                assistant.start_assist(assist_id, window, cx);
1787            })?;
1788
1789            Ok(ProjectTransaction::default())
1790        })
1791    }
1792}
1793
1794fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1795    ranges.sort_unstable_by(|a, b| {
1796        a.start
1797            .cmp(&b.start, buffer)
1798            .then_with(|| b.end.cmp(&a.end, buffer))
1799    });
1800
1801    let mut ix = 0;
1802    while ix + 1 < ranges.len() {
1803        let b = ranges[ix + 1].clone();
1804        let a = &mut ranges[ix];
1805        if a.end.cmp(&b.start, buffer).is_gt() {
1806            if a.end.cmp(&b.end, buffer).is_lt() {
1807                a.end = b.end;
1808            }
1809            ranges.remove(ix + 1);
1810        } else {
1811            ix += 1;
1812        }
1813    }
1814}