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