inline_assistant.rs

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