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