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