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