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