inline_assistant.rs

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