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