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