inline_assistant.rs

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