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;
  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 = AgentSettings::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 = AgentSettings::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, newest_selection) = editor.update(cx, |editor, cx| {
 342            let selections = editor.selections.all::<Point>(cx);
 343            let newest_selection = editor.selections.newest::<Point>(cx);
 344            (editor.snapshot(window, cx), selections, newest_selection)
 345        });
 346
 347        // Check if there is already an inline assistant that contains the
 348        // newest selection, if there is, focus it
 349        if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 350            for assist_id in &editor_assists.assist_ids {
 351                let assist = &self.assists[assist_id];
 352                let range = assist.range.to_point(&snapshot.buffer_snapshot);
 353                if range.start.row <= newest_selection.start.row
 354                    && newest_selection.end.row <= range.end.row
 355                {
 356                    self.focus_assist(*assist_id, window, cx);
 357                    return;
 358                }
 359            }
 360        }
 361
 362        let mut selections = Vec::<Selection<Point>>::new();
 363        let mut newest_selection = None;
 364        for mut selection in initial_selections {
 365            if selection.end > selection.start {
 366                selection.start.column = 0;
 367                // If the selection ends at the start of the line, we don't want to include it.
 368                if selection.end.column == 0 {
 369                    selection.end.row -= 1;
 370                }
 371                selection.end.column = snapshot
 372                    .buffer_snapshot
 373                    .line_len(MultiBufferRow(selection.end.row));
 374            } else if let Some(fold) =
 375                snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
 376            {
 377                selection.start = fold.range().start;
 378                selection.end = fold.range().end;
 379                if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot.max_row() {
 380                    let chars = snapshot
 381                        .buffer_snapshot
 382                        .chars_at(Point::new(selection.end.row + 1, 0));
 383
 384                    for c in chars {
 385                        if c == '\n' {
 386                            break;
 387                        }
 388                        if c.is_whitespace() {
 389                            continue;
 390                        }
 391                        if snapshot
 392                            .language_at(selection.end)
 393                            .is_some_and(|language| language.config().brackets.is_closing_brace(c))
 394                        {
 395                            selection.end.row += 1;
 396                            selection.end.column = snapshot
 397                                .buffer_snapshot
 398                                .line_len(MultiBufferRow(selection.end.row));
 399                        }
 400                    }
 401                }
 402            }
 403
 404            if let Some(prev_selection) = selections.last_mut() {
 405                if selection.start <= prev_selection.end {
 406                    prev_selection.end = selection.end;
 407                    continue;
 408                }
 409            }
 410
 411            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 412            if selection.id > latest_selection.id {
 413                *latest_selection = selection.clone();
 414            }
 415            selections.push(selection);
 416        }
 417        let snapshot = &snapshot.buffer_snapshot;
 418        let newest_selection = newest_selection.unwrap();
 419
 420        let mut codegen_ranges = Vec::new();
 421        for (buffer, buffer_range, excerpt_id) in
 422            snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
 423                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 424            }))
 425        {
 426            let anchor_range = Anchor::range_in_buffer(
 427                excerpt_id,
 428                buffer.remote_id(),
 429                buffer.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
 430            );
 431
 432            codegen_ranges.push(anchor_range);
 433
 434            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
 435                self.telemetry.report_assistant_event(AssistantEventData {
 436                    conversation_id: None,
 437                    kind: AssistantKind::Inline,
 438                    phase: AssistantPhase::Invoked,
 439                    message_id: None,
 440                    model: model.model.telemetry_id(),
 441                    model_provider: model.provider.id().to_string(),
 442                    response_latency: None,
 443                    error_message: None,
 444                    language_name: buffer.language().map(|language| language.name().to_proto()),
 445                });
 446            }
 447        }
 448
 449        let assist_group_id = self.next_assist_group_id.post_inc();
 450        let prompt_buffer = cx.new(|cx| {
 451            MultiBuffer::singleton(
 452                cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
 453                cx,
 454            )
 455        });
 456
 457        let mut assists = Vec::new();
 458        let mut assist_to_focus = None;
 459        for range in codegen_ranges {
 460            let assist_id = self.next_assist_id.post_inc();
 461            let codegen = cx.new(|cx| {
 462                BufferCodegen::new(
 463                    editor.read(cx).buffer().clone(),
 464                    range.clone(),
 465                    None,
 466                    context_store.clone(),
 467                    project.clone(),
 468                    prompt_store.clone(),
 469                    self.telemetry.clone(),
 470                    self.prompt_builder.clone(),
 471                    cx,
 472                )
 473            });
 474
 475            let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 476            let prompt_editor = cx.new(|cx| {
 477                PromptEditor::new_buffer(
 478                    assist_id,
 479                    editor_margins,
 480                    self.prompt_history.clone(),
 481                    prompt_buffer.clone(),
 482                    codegen.clone(),
 483                    self.fs.clone(),
 484                    context_store.clone(),
 485                    workspace.clone(),
 486                    thread_store.clone(),
 487                    text_thread_store.clone(),
 488                    window,
 489                    cx,
 490                )
 491            });
 492
 493            if assist_to_focus.is_none() {
 494                let focus_assist = if newest_selection.reversed {
 495                    range.start.to_point(&snapshot) == newest_selection.start
 496                } else {
 497                    range.end.to_point(&snapshot) == newest_selection.end
 498                };
 499                if focus_assist {
 500                    assist_to_focus = Some(assist_id);
 501                }
 502            }
 503
 504            let [prompt_block_id, end_block_id] =
 505                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 506
 507            assists.push((
 508                assist_id,
 509                range,
 510                prompt_editor,
 511                prompt_block_id,
 512                end_block_id,
 513            ));
 514        }
 515
 516        let editor_assists = self
 517            .assists_by_editor
 518            .entry(editor.downgrade())
 519            .or_insert_with(|| EditorInlineAssists::new(&editor, window, cx));
 520        let mut assist_group = InlineAssistGroup::new();
 521        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
 522            let codegen = prompt_editor.read(cx).codegen().clone();
 523
 524            self.assists.insert(
 525                assist_id,
 526                InlineAssist::new(
 527                    assist_id,
 528                    assist_group_id,
 529                    editor,
 530                    &prompt_editor,
 531                    prompt_block_id,
 532                    end_block_id,
 533                    range,
 534                    codegen,
 535                    workspace.clone(),
 536                    window,
 537                    cx,
 538                ),
 539            );
 540            assist_group.assist_ids.push(assist_id);
 541            editor_assists.assist_ids.push(assist_id);
 542        }
 543        self.assist_groups.insert(assist_group_id, assist_group);
 544
 545        if let Some(assist_id) = assist_to_focus {
 546            self.focus_assist(assist_id, window, cx);
 547        }
 548    }
 549
 550    pub fn suggest_assist(
 551        &mut self,
 552        editor: &Entity<Editor>,
 553        mut range: Range<Anchor>,
 554        initial_prompt: String,
 555        initial_transaction_id: Option<TransactionId>,
 556        focus: bool,
 557        workspace: Entity<Workspace>,
 558        prompt_store: Option<Entity<PromptStore>>,
 559        thread_store: Option<WeakEntity<ThreadStore>>,
 560        text_thread_store: Option<WeakEntity<TextThreadStore>>,
 561        window: &mut Window,
 562        cx: &mut App,
 563    ) -> InlineAssistId {
 564        let assist_group_id = self.next_assist_group_id.post_inc();
 565        let prompt_buffer = cx.new(|cx| Buffer::local(&initial_prompt, cx));
 566        let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 567
 568        let assist_id = self.next_assist_id.post_inc();
 569
 570        let buffer = editor.read(cx).buffer().clone();
 571        {
 572            let snapshot = buffer.read(cx).read(cx);
 573            range.start = range.start.bias_left(&snapshot);
 574            range.end = range.end.bias_right(&snapshot);
 575        }
 576
 577        let project = workspace.read(cx).project().downgrade();
 578        let context_store = cx.new(|_cx| ContextStore::new(project.clone(), thread_store.clone()));
 579
 580        let codegen = cx.new(|cx| {
 581            BufferCodegen::new(
 582                editor.read(cx).buffer().clone(),
 583                range.clone(),
 584                initial_transaction_id,
 585                context_store.clone(),
 586                project,
 587                prompt_store,
 588                self.telemetry.clone(),
 589                self.prompt_builder.clone(),
 590                cx,
 591            )
 592        });
 593
 594        let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
 595        let prompt_editor = cx.new(|cx| {
 596            PromptEditor::new_buffer(
 597                assist_id,
 598                editor_margins,
 599                self.prompt_history.clone(),
 600                prompt_buffer.clone(),
 601                codegen.clone(),
 602                self.fs.clone(),
 603                context_store,
 604                workspace.downgrade(),
 605                thread_store,
 606                text_thread_store,
 607                window,
 608                cx,
 609            )
 610        });
 611
 612        let [prompt_block_id, end_block_id] =
 613            self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 614
 615        let editor_assists = self
 616            .assists_by_editor
 617            .entry(editor.downgrade())
 618            .or_insert_with(|| EditorInlineAssists::new(&editor, window, cx));
 619
 620        let mut assist_group = InlineAssistGroup::new();
 621        self.assists.insert(
 622            assist_id,
 623            InlineAssist::new(
 624                assist_id,
 625                assist_group_id,
 626                editor,
 627                &prompt_editor,
 628                prompt_block_id,
 629                end_block_id,
 630                range,
 631                codegen.clone(),
 632                workspace.downgrade(),
 633                window,
 634                cx,
 635            ),
 636        );
 637        assist_group.assist_ids.push(assist_id);
 638        editor_assists.assist_ids.push(assist_id);
 639        self.assist_groups.insert(assist_group_id, assist_group);
 640
 641        if focus {
 642            self.focus_assist(assist_id, window, cx);
 643        }
 644
 645        assist_id
 646    }
 647
 648    fn insert_assist_blocks(
 649        &self,
 650        editor: &Entity<Editor>,
 651        range: &Range<Anchor>,
 652        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
 653        cx: &mut App,
 654    ) -> [CustomBlockId; 2] {
 655        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 656            prompt_editor
 657                .editor
 658                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 659        });
 660        let assist_blocks = vec![
 661            BlockProperties {
 662                style: BlockStyle::Sticky,
 663                placement: BlockPlacement::Above(range.start),
 664                height: Some(prompt_editor_height),
 665                render: build_assist_editor_renderer(prompt_editor),
 666                priority: 0,
 667                render_in_minimap: false,
 668            },
 669            BlockProperties {
 670                style: BlockStyle::Sticky,
 671                placement: BlockPlacement::Below(range.end),
 672                height: None,
 673                render: Arc::new(|cx| {
 674                    v_flex()
 675                        .h_full()
 676                        .w_full()
 677                        .border_t_1()
 678                        .border_color(cx.theme().status().info_border)
 679                        .into_any_element()
 680                }),
 681                priority: 0,
 682                render_in_minimap: false,
 683            },
 684        ];
 685
 686        editor.update(cx, |editor, cx| {
 687            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 688            [block_ids[0], block_ids[1]]
 689        })
 690    }
 691
 692    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 693        let assist = &self.assists[&assist_id];
 694        let Some(decorations) = assist.decorations.as_ref() else {
 695            return;
 696        };
 697        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 698        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 699
 700        assist_group.active_assist_id = Some(assist_id);
 701        if assist_group.linked {
 702            for assist_id in &assist_group.assist_ids {
 703                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 704                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 705                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 706                    });
 707                }
 708            }
 709        }
 710
 711        assist
 712            .editor
 713            .update(cx, |editor, cx| {
 714                let scroll_top = editor.scroll_position(cx).y;
 715                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 716                let prompt_row = editor
 717                    .row_for_block(decorations.prompt_block_id, cx)
 718                    .unwrap()
 719                    .0 as f32;
 720
 721                if (scroll_top..scroll_bottom).contains(&prompt_row) {
 722                    editor_assists.scroll_lock = Some(InlineAssistScrollLock {
 723                        assist_id,
 724                        distance_from_top: prompt_row - scroll_top,
 725                    });
 726                } else {
 727                    editor_assists.scroll_lock = None;
 728                }
 729            })
 730            .ok();
 731    }
 732
 733    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 734        let assist = &self.assists[&assist_id];
 735        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 736        if assist_group.active_assist_id == Some(assist_id) {
 737            assist_group.active_assist_id = None;
 738            if assist_group.linked {
 739                for assist_id in &assist_group.assist_ids {
 740                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 741                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 742                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 743                        });
 744                    }
 745                }
 746            }
 747        }
 748    }
 749
 750    fn handle_prompt_editor_event(
 751        &mut self,
 752        prompt_editor: Entity<PromptEditor<BufferCodegen>>,
 753        event: &PromptEditorEvent,
 754        window: &mut Window,
 755        cx: &mut App,
 756    ) {
 757        let assist_id = prompt_editor.read(cx).id();
 758        match event {
 759            PromptEditorEvent::StartRequested => {
 760                self.start_assist(assist_id, window, cx);
 761            }
 762            PromptEditorEvent::StopRequested => {
 763                self.stop_assist(assist_id, cx);
 764            }
 765            PromptEditorEvent::ConfirmRequested { execute: _ } => {
 766                self.finish_assist(assist_id, false, window, cx);
 767            }
 768            PromptEditorEvent::CancelRequested => {
 769                self.finish_assist(assist_id, true, window, cx);
 770            }
 771            PromptEditorEvent::DismissRequested => {
 772                self.dismiss_assist(assist_id, window, cx);
 773            }
 774            PromptEditorEvent::Resized { .. } => {
 775                // This only matters for the terminal inline assistant
 776            }
 777        }
 778    }
 779
 780    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 781        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 782            return;
 783        };
 784
 785        if editor.read(cx).selections.count() == 1 {
 786            let (selection, buffer) = editor.update(cx, |editor, cx| {
 787                (
 788                    editor.selections.newest::<usize>(cx),
 789                    editor.buffer().read(cx).snapshot(cx),
 790                )
 791            });
 792            for assist_id in &editor_assists.assist_ids {
 793                let assist = &self.assists[assist_id];
 794                let assist_range = assist.range.to_offset(&buffer);
 795                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 796                {
 797                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 798                        self.dismiss_assist(*assist_id, window, cx);
 799                    } else {
 800                        self.finish_assist(*assist_id, false, window, cx);
 801                    }
 802
 803                    return;
 804                }
 805            }
 806        }
 807
 808        cx.propagate();
 809    }
 810
 811    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 812        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 813            return;
 814        };
 815
 816        if editor.read(cx).selections.count() == 1 {
 817            let (selection, buffer) = editor.update(cx, |editor, cx| {
 818                (
 819                    editor.selections.newest::<usize>(cx),
 820                    editor.buffer().read(cx).snapshot(cx),
 821                )
 822            });
 823            let mut closest_assist_fallback = None;
 824            for assist_id in &editor_assists.assist_ids {
 825                let assist = &self.assists[assist_id];
 826                let assist_range = assist.range.to_offset(&buffer);
 827                if assist.decorations.is_some() {
 828                    if assist_range.contains(&selection.start)
 829                        && assist_range.contains(&selection.end)
 830                    {
 831                        self.focus_assist(*assist_id, window, cx);
 832                        return;
 833                    } else {
 834                        let distance_from_selection = assist_range
 835                            .start
 836                            .abs_diff(selection.start)
 837                            .min(assist_range.start.abs_diff(selection.end))
 838                            + assist_range
 839                                .end
 840                                .abs_diff(selection.start)
 841                                .min(assist_range.end.abs_diff(selection.end));
 842                        match closest_assist_fallback {
 843                            Some((_, old_distance)) => {
 844                                if distance_from_selection < old_distance {
 845                                    closest_assist_fallback =
 846                                        Some((assist_id, distance_from_selection));
 847                                }
 848                            }
 849                            None => {
 850                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 851                            }
 852                        }
 853                    }
 854                }
 855            }
 856
 857            if let Some((&assist_id, _)) = closest_assist_fallback {
 858                self.focus_assist(assist_id, window, cx);
 859            }
 860        }
 861
 862        cx.propagate();
 863    }
 864
 865    fn handle_editor_release(
 866        &mut self,
 867        editor: WeakEntity<Editor>,
 868        window: &mut Window,
 869        cx: &mut App,
 870    ) {
 871        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 872            for assist_id in editor_assists.assist_ids.clone() {
 873                self.finish_assist(assist_id, true, window, cx);
 874            }
 875        }
 876    }
 877
 878    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 879        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 880            return;
 881        };
 882        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 883            return;
 884        };
 885        let assist = &self.assists[&scroll_lock.assist_id];
 886        let Some(decorations) = assist.decorations.as_ref() else {
 887            return;
 888        };
 889
 890        editor.update(cx, |editor, cx| {
 891            let scroll_position = editor.scroll_position(cx);
 892            let target_scroll_top = editor
 893                .row_for_block(decorations.prompt_block_id, cx)
 894                .unwrap()
 895                .0 as f32
 896                - scroll_lock.distance_from_top;
 897            if target_scroll_top != scroll_position.y {
 898                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 899            }
 900        });
 901    }
 902
 903    fn handle_editor_event(
 904        &mut self,
 905        editor: Entity<Editor>,
 906        event: &EditorEvent,
 907        window: &mut Window,
 908        cx: &mut App,
 909    ) {
 910        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 911            return;
 912        };
 913
 914        match event {
 915            EditorEvent::Edited { transaction_id } => {
 916                let buffer = editor.read(cx).buffer().read(cx);
 917                let edited_ranges =
 918                    buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
 919                let snapshot = buffer.snapshot(cx);
 920
 921                for assist_id in editor_assists.assist_ids.clone() {
 922                    let assist = &self.assists[&assist_id];
 923                    if matches!(
 924                        assist.codegen.read(cx).status(cx),
 925                        CodegenStatus::Error(_) | CodegenStatus::Done
 926                    ) {
 927                        let assist_range = assist.range.to_offset(&snapshot);
 928                        if edited_ranges
 929                            .iter()
 930                            .any(|range| range.overlaps(&assist_range))
 931                        {
 932                            self.finish_assist(assist_id, false, window, cx);
 933                        }
 934                    }
 935                }
 936            }
 937            EditorEvent::ScrollPositionChanged { .. } => {
 938                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 939                    let assist = &self.assists[&scroll_lock.assist_id];
 940                    if let Some(decorations) = assist.decorations.as_ref() {
 941                        let distance_from_top = editor.update(cx, |editor, cx| {
 942                            let scroll_top = editor.scroll_position(cx).y;
 943                            let prompt_row = editor
 944                                .row_for_block(decorations.prompt_block_id, cx)
 945                                .unwrap()
 946                                .0 as f32;
 947                            prompt_row - scroll_top
 948                        });
 949
 950                        if distance_from_top != scroll_lock.distance_from_top {
 951                            editor_assists.scroll_lock = None;
 952                        }
 953                    }
 954                }
 955            }
 956            EditorEvent::SelectionsChanged { .. } => {
 957                for assist_id in editor_assists.assist_ids.clone() {
 958                    let assist = &self.assists[&assist_id];
 959                    if let Some(decorations) = assist.decorations.as_ref() {
 960                        if decorations
 961                            .prompt_editor
 962                            .focus_handle(cx)
 963                            .is_focused(window)
 964                        {
 965                            return;
 966                        }
 967                    }
 968                }
 969
 970                editor_assists.scroll_lock = None;
 971            }
 972            _ => {}
 973        }
 974    }
 975
 976    pub fn finish_assist(
 977        &mut self,
 978        assist_id: InlineAssistId,
 979        undo: bool,
 980        window: &mut Window,
 981        cx: &mut App,
 982    ) {
 983        if let Some(assist) = self.assists.get(&assist_id) {
 984            let assist_group_id = assist.group_id;
 985            if self.assist_groups[&assist_group_id].linked {
 986                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
 987                    self.finish_assist(assist_id, undo, window, cx);
 988                }
 989                return;
 990            }
 991        }
 992
 993        self.dismiss_assist(assist_id, window, cx);
 994
 995        if let Some(assist) = self.assists.remove(&assist_id) {
 996            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
 997            {
 998                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 999                if entry.get().assist_ids.is_empty() {
1000                    entry.remove();
1001                }
1002            }
1003
1004            if let hash_map::Entry::Occupied(mut entry) =
1005                self.assists_by_editor.entry(assist.editor.clone())
1006            {
1007                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1008                if entry.get().assist_ids.is_empty() {
1009                    entry.remove();
1010                    if let Some(editor) = assist.editor.upgrade() {
1011                        self.update_editor_highlights(&editor, cx);
1012                    }
1013                } else {
1014                    entry.get().highlight_updates.send(()).ok();
1015                }
1016            }
1017
1018            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1019            let message_id = active_alternative.read(cx).message_id.clone();
1020
1021            if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1022                let language_name = assist.editor.upgrade().and_then(|editor| {
1023                    let multibuffer = editor.read(cx).buffer().read(cx);
1024                    let snapshot = multibuffer.snapshot(cx);
1025                    let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
1026                    ranges
1027                        .first()
1028                        .and_then(|(buffer, _, _)| buffer.language())
1029                        .map(|language| language.name())
1030                });
1031                report_assistant_event(
1032                    AssistantEventData {
1033                        conversation_id: None,
1034                        kind: AssistantKind::Inline,
1035                        message_id,
1036                        phase: if undo {
1037                            AssistantPhase::Rejected
1038                        } else {
1039                            AssistantPhase::Accepted
1040                        },
1041                        model: model.model.telemetry_id(),
1042                        model_provider: model.model.provider_id().to_string(),
1043                        response_latency: None,
1044                        error_message: None,
1045                        language_name: language_name.map(|name| name.to_proto()),
1046                    },
1047                    Some(self.telemetry.clone()),
1048                    cx.http_client(),
1049                    model.model.api_key(cx),
1050                    cx.background_executor(),
1051                );
1052            }
1053
1054            if undo {
1055                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1056            } else {
1057                self.confirmed_assists.insert(assist_id, active_alternative);
1058            }
1059        }
1060    }
1061
1062    fn dismiss_assist(
1063        &mut self,
1064        assist_id: InlineAssistId,
1065        window: &mut Window,
1066        cx: &mut App,
1067    ) -> bool {
1068        let Some(assist) = self.assists.get_mut(&assist_id) else {
1069            return false;
1070        };
1071        let Some(editor) = assist.editor.upgrade() else {
1072            return false;
1073        };
1074        let Some(decorations) = assist.decorations.take() else {
1075            return false;
1076        };
1077
1078        editor.update(cx, |editor, cx| {
1079            let mut to_remove = decorations.removed_line_block_ids;
1080            to_remove.insert(decorations.prompt_block_id);
1081            to_remove.insert(decorations.end_block_id);
1082            editor.remove_blocks(to_remove, None, cx);
1083        });
1084
1085        if decorations
1086            .prompt_editor
1087            .focus_handle(cx)
1088            .contains_focused(window, cx)
1089        {
1090            self.focus_next_assist(assist_id, window, cx);
1091        }
1092
1093        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1094            if editor_assists
1095                .scroll_lock
1096                .as_ref()
1097                .map_or(false, |lock| lock.assist_id == assist_id)
1098            {
1099                editor_assists.scroll_lock = None;
1100            }
1101            editor_assists.highlight_updates.send(()).ok();
1102        }
1103
1104        true
1105    }
1106
1107    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1108        let Some(assist) = self.assists.get(&assist_id) else {
1109            return;
1110        };
1111
1112        let assist_group = &self.assist_groups[&assist.group_id];
1113        let assist_ix = assist_group
1114            .assist_ids
1115            .iter()
1116            .position(|id| *id == assist_id)
1117            .unwrap();
1118        let assist_ids = assist_group
1119            .assist_ids
1120            .iter()
1121            .skip(assist_ix + 1)
1122            .chain(assist_group.assist_ids.iter().take(assist_ix));
1123
1124        for assist_id in assist_ids {
1125            let assist = &self.assists[assist_id];
1126            if assist.decorations.is_some() {
1127                self.focus_assist(*assist_id, window, cx);
1128                return;
1129            }
1130        }
1131
1132        assist
1133            .editor
1134            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1135            .ok();
1136    }
1137
1138    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1139        let Some(assist) = self.assists.get(&assist_id) else {
1140            return;
1141        };
1142
1143        if let Some(decorations) = assist.decorations.as_ref() {
1144            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1145                prompt_editor.editor.update(cx, |editor, cx| {
1146                    window.focus(&editor.focus_handle(cx));
1147                    editor.select_all(&SelectAll, window, cx);
1148                })
1149            });
1150        }
1151
1152        self.scroll_to_assist(assist_id, window, cx);
1153    }
1154
1155    pub fn scroll_to_assist(
1156        &mut self,
1157        assist_id: InlineAssistId,
1158        window: &mut Window,
1159        cx: &mut App,
1160    ) {
1161        let Some(assist) = self.assists.get(&assist_id) else {
1162            return;
1163        };
1164        let Some(editor) = assist.editor.upgrade() else {
1165            return;
1166        };
1167
1168        let position = assist.range.start;
1169        editor.update(cx, |editor, cx| {
1170            editor.change_selections(None, window, cx, |selections| {
1171                selections.select_anchor_ranges([position..position])
1172            });
1173
1174            let mut scroll_target_top;
1175            let mut scroll_target_bottom;
1176            if let Some(decorations) = assist.decorations.as_ref() {
1177                scroll_target_top = editor
1178                    .row_for_block(decorations.prompt_block_id, cx)
1179                    .unwrap()
1180                    .0 as f32;
1181                scroll_target_bottom = editor
1182                    .row_for_block(decorations.end_block_id, cx)
1183                    .unwrap()
1184                    .0 as f32;
1185            } else {
1186                let snapshot = editor.snapshot(window, cx);
1187                let start_row = assist
1188                    .range
1189                    .start
1190                    .to_display_point(&snapshot.display_snapshot)
1191                    .row();
1192                scroll_target_top = start_row.0 as f32;
1193                scroll_target_bottom = scroll_target_top + 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                    HighlightStyle {
1357                        fade_out: Some(0.6),
1358                        ..Default::default()
1359                    },
1360                    cx,
1361                );
1362            }
1363
1364            editor.clear_row_highlights::<InlineAssist>();
1365            for row_range in inserted_row_ranges {
1366                editor.highlight_rows::<InlineAssist>(
1367                    row_range,
1368                    cx.theme().status().info_background,
1369                    Default::default(),
1370                    cx,
1371                );
1372            }
1373        });
1374    }
1375
1376    fn update_editor_blocks(
1377        &mut self,
1378        editor: &Entity<Editor>,
1379        assist_id: InlineAssistId,
1380        window: &mut Window,
1381        cx: &mut App,
1382    ) {
1383        let Some(assist) = self.assists.get_mut(&assist_id) else {
1384            return;
1385        };
1386        let Some(decorations) = assist.decorations.as_mut() else {
1387            return;
1388        };
1389
1390        let codegen = assist.codegen.read(cx);
1391        let old_snapshot = codegen.snapshot(cx);
1392        let old_buffer = codegen.old_buffer(cx);
1393        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1394
1395        editor.update(cx, |editor, cx| {
1396            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1397            editor.remove_blocks(old_blocks, None, cx);
1398
1399            let mut new_blocks = Vec::new();
1400            for (new_row, old_row_range) in deleted_row_ranges {
1401                let (_, buffer_start) = old_snapshot
1402                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1403                    .unwrap();
1404                let (_, buffer_end) = old_snapshot
1405                    .point_to_buffer_offset(Point::new(
1406                        *old_row_range.end(),
1407                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1408                    ))
1409                    .unwrap();
1410
1411                let deleted_lines_editor = cx.new(|cx| {
1412                    let multi_buffer =
1413                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1414                    multi_buffer.update(cx, |multi_buffer, cx| {
1415                        multi_buffer.push_excerpts(
1416                            old_buffer.clone(),
1417                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1418                            cx,
1419                        );
1420                    });
1421
1422                    enum DeletedLines {}
1423                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1424                    editor.disable_scrollbars_and_minimap(window, cx);
1425                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1426                    editor.set_show_wrap_guides(false, cx);
1427                    editor.set_show_gutter(false, cx);
1428                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1429                    editor.set_read_only(true);
1430                    editor.set_show_edit_predictions(Some(false), window, cx);
1431                    editor.highlight_rows::<DeletedLines>(
1432                        Anchor::min()..Anchor::max(),
1433                        cx.theme().status().deleted_background,
1434                        Default::default(),
1435                        cx,
1436                    );
1437                    editor
1438                });
1439
1440                let height =
1441                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1442                new_blocks.push(BlockProperties {
1443                    placement: BlockPlacement::Above(new_row),
1444                    height: Some(height),
1445                    style: BlockStyle::Flex,
1446                    render: Arc::new(move |cx| {
1447                        div()
1448                            .block_mouse_except_scroll()
1449                            .bg(cx.theme().status().deleted_background)
1450                            .size_full()
1451                            .h(height as f32 * cx.window.line_height())
1452                            .pl(cx.margins.gutter.full_width())
1453                            .child(deleted_lines_editor.clone())
1454                            .into_any_element()
1455                    }),
1456                    priority: 0,
1457                    render_in_minimap: false,
1458                });
1459            }
1460
1461            decorations.removed_line_block_ids = editor
1462                .insert_blocks(new_blocks, None, cx)
1463                .into_iter()
1464                .collect();
1465        })
1466    }
1467
1468    fn resolve_inline_assist_target(
1469        workspace: &mut Workspace,
1470        agent_panel: Option<Entity<AgentPanel>>,
1471        window: &mut Window,
1472        cx: &mut App,
1473    ) -> Option<InlineAssistTarget> {
1474        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
1475            if terminal_panel
1476                .read(cx)
1477                .focus_handle(cx)
1478                .contains_focused(window, cx)
1479            {
1480                if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1481                    pane.read(cx)
1482                        .active_item()
1483                        .and_then(|t| t.downcast::<TerminalView>())
1484                }) {
1485                    return Some(InlineAssistTarget::Terminal(terminal_view));
1486                }
1487            }
1488        }
1489
1490        let context_editor = agent_panel
1491            .and_then(|panel| panel.read(cx).active_context_editor())
1492            .and_then(|editor| {
1493                let editor = &editor.read(cx).editor().clone();
1494                if editor.read(cx).is_focused(window) {
1495                    Some(editor.clone())
1496                } else {
1497                    None
1498                }
1499            });
1500
1501        if let Some(context_editor) = context_editor {
1502            Some(InlineAssistTarget::Editor(context_editor))
1503        } else if let Some(workspace_editor) = workspace
1504            .active_item(cx)
1505            .and_then(|item| item.act_as::<Editor>(cx))
1506        {
1507            Some(InlineAssistTarget::Editor(workspace_editor))
1508        } else if let Some(terminal_view) = workspace
1509            .active_item(cx)
1510            .and_then(|item| item.act_as::<TerminalView>(cx))
1511        {
1512            Some(InlineAssistTarget::Terminal(terminal_view))
1513        } else {
1514            None
1515        }
1516    }
1517}
1518
1519struct EditorInlineAssists {
1520    assist_ids: Vec<InlineAssistId>,
1521    scroll_lock: Option<InlineAssistScrollLock>,
1522    highlight_updates: async_watch::Sender<()>,
1523    _update_highlights: Task<Result<()>>,
1524    _subscriptions: Vec<gpui::Subscription>,
1525}
1526
1527struct InlineAssistScrollLock {
1528    assist_id: InlineAssistId,
1529    distance_from_top: f32,
1530}
1531
1532impl EditorInlineAssists {
1533    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1534        let (highlight_updates_tx, mut highlight_updates_rx) = async_watch::channel(());
1535        Self {
1536            assist_ids: Vec::new(),
1537            scroll_lock: None,
1538            highlight_updates: highlight_updates_tx,
1539            _update_highlights: cx.spawn({
1540                let editor = editor.downgrade();
1541                async move |cx| {
1542                    while let Ok(()) = highlight_updates_rx.changed().await {
1543                        let editor = editor.upgrade().context("editor was dropped")?;
1544                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1545                            assistant.update_editor_highlights(&editor, cx);
1546                        })?;
1547                    }
1548                    Ok(())
1549                }
1550            }),
1551            _subscriptions: vec![
1552                cx.observe_release_in(editor, window, {
1553                    let editor = editor.downgrade();
1554                    |_, window, cx| {
1555                        InlineAssistant::update_global(cx, |this, cx| {
1556                            this.handle_editor_release(editor, window, cx);
1557                        })
1558                    }
1559                }),
1560                window.observe(editor, cx, move |editor, window, cx| {
1561                    InlineAssistant::update_global(cx, |this, cx| {
1562                        this.handle_editor_change(editor, window, cx)
1563                    })
1564                }),
1565                window.subscribe(editor, cx, move |editor, event, window, cx| {
1566                    InlineAssistant::update_global(cx, |this, cx| {
1567                        this.handle_editor_event(editor, event, window, cx)
1568                    })
1569                }),
1570                editor.update(cx, |editor, cx| {
1571                    let editor_handle = cx.entity().downgrade();
1572                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1573                        InlineAssistant::update_global(cx, |this, cx| {
1574                            if let Some(editor) = editor_handle.upgrade() {
1575                                this.handle_editor_newline(editor, window, cx)
1576                            }
1577                        })
1578                    })
1579                }),
1580                editor.update(cx, |editor, cx| {
1581                    let editor_handle = cx.entity().downgrade();
1582                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1583                        InlineAssistant::update_global(cx, |this, cx| {
1584                            if let Some(editor) = editor_handle.upgrade() {
1585                                this.handle_editor_cancel(editor, window, cx)
1586                            }
1587                        })
1588                    })
1589                }),
1590            ],
1591        }
1592    }
1593}
1594
1595struct InlineAssistGroup {
1596    assist_ids: Vec<InlineAssistId>,
1597    linked: bool,
1598    active_assist_id: Option<InlineAssistId>,
1599}
1600
1601impl InlineAssistGroup {
1602    fn new() -> Self {
1603        Self {
1604            assist_ids: Vec::new(),
1605            linked: true,
1606            active_assist_id: None,
1607        }
1608    }
1609}
1610
1611fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1612    let editor = editor.clone();
1613
1614    Arc::new(move |cx: &mut BlockContext| {
1615        let editor_margins = editor.read(cx).editor_margins();
1616
1617        *editor_margins.lock() = *cx.margins;
1618        editor.clone().into_any_element()
1619    })
1620}
1621
1622#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1623struct InlineAssistGroupId(usize);
1624
1625impl InlineAssistGroupId {
1626    fn post_inc(&mut self) -> InlineAssistGroupId {
1627        let id = *self;
1628        self.0 += 1;
1629        id
1630    }
1631}
1632
1633pub struct InlineAssist {
1634    group_id: InlineAssistGroupId,
1635    range: Range<Anchor>,
1636    editor: WeakEntity<Editor>,
1637    decorations: Option<InlineAssistDecorations>,
1638    codegen: Entity<BufferCodegen>,
1639    _subscriptions: Vec<Subscription>,
1640    workspace: WeakEntity<Workspace>,
1641}
1642
1643impl InlineAssist {
1644    fn new(
1645        assist_id: InlineAssistId,
1646        group_id: InlineAssistGroupId,
1647        editor: &Entity<Editor>,
1648        prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1649        prompt_block_id: CustomBlockId,
1650        end_block_id: CustomBlockId,
1651        range: Range<Anchor>,
1652        codegen: Entity<BufferCodegen>,
1653        workspace: WeakEntity<Workspace>,
1654        window: &mut Window,
1655        cx: &mut App,
1656    ) -> Self {
1657        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1658        InlineAssist {
1659            group_id,
1660            editor: editor.downgrade(),
1661            decorations: Some(InlineAssistDecorations {
1662                prompt_block_id,
1663                prompt_editor: prompt_editor.clone(),
1664                removed_line_block_ids: HashSet::default(),
1665                end_block_id,
1666            }),
1667            range,
1668            codegen: codegen.clone(),
1669            workspace: workspace.clone(),
1670            _subscriptions: vec![
1671                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1672                    InlineAssistant::update_global(cx, |this, cx| {
1673                        this.handle_prompt_editor_focus_in(assist_id, cx)
1674                    })
1675                }),
1676                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1677                    InlineAssistant::update_global(cx, |this, cx| {
1678                        this.handle_prompt_editor_focus_out(assist_id, cx)
1679                    })
1680                }),
1681                window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1682                    InlineAssistant::update_global(cx, |this, cx| {
1683                        this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1684                    })
1685                }),
1686                window.observe(&codegen, cx, {
1687                    let editor = editor.downgrade();
1688                    move |_, window, cx| {
1689                        if let Some(editor) = editor.upgrade() {
1690                            InlineAssistant::update_global(cx, |this, cx| {
1691                                if let Some(editor_assists) =
1692                                    this.assists_by_editor.get(&editor.downgrade())
1693                                {
1694                                    editor_assists.highlight_updates.send(()).ok();
1695                                }
1696
1697                                this.update_editor_blocks(&editor, assist_id, window, cx);
1698                            })
1699                        }
1700                    }
1701                }),
1702                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1703                    InlineAssistant::update_global(cx, |this, cx| match event {
1704                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1705                        CodegenEvent::Finished => {
1706                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
1707                                assist
1708                            } else {
1709                                return;
1710                            };
1711
1712                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx) {
1713                                if assist.decorations.is_none() {
1714                                    if let Some(workspace) = assist.workspace.upgrade() {
1715                                        let error = format!("Inline assistant error: {}", error);
1716                                        workspace.update(cx, |workspace, cx| {
1717                                            struct InlineAssistantError;
1718
1719                                            let id =
1720                                                NotificationId::composite::<InlineAssistantError>(
1721                                                    assist_id.0,
1722                                                );
1723
1724                                            workspace.show_toast(Toast::new(id, error), cx);
1725                                        })
1726                                    }
1727                                }
1728                            }
1729
1730                            if assist.decorations.is_none() {
1731                                this.finish_assist(assist_id, false, window, cx);
1732                            }
1733                        }
1734                    })
1735                }),
1736            ],
1737        }
1738    }
1739
1740    fn user_prompt(&self, cx: &App) -> Option<String> {
1741        let decorations = self.decorations.as_ref()?;
1742        Some(decorations.prompt_editor.read(cx).prompt(cx))
1743    }
1744}
1745
1746struct InlineAssistDecorations {
1747    prompt_block_id: CustomBlockId,
1748    prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1749    removed_line_block_ids: HashSet<CustomBlockId>,
1750    end_block_id: CustomBlockId,
1751}
1752
1753struct AssistantCodeActionProvider {
1754    editor: WeakEntity<Editor>,
1755    workspace: WeakEntity<Workspace>,
1756    thread_store: Option<WeakEntity<ThreadStore>>,
1757    text_thread_store: Option<WeakEntity<TextThreadStore>>,
1758}
1759
1760const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant2";
1761
1762impl CodeActionProvider for AssistantCodeActionProvider {
1763    fn id(&self) -> Arc<str> {
1764        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1765    }
1766
1767    fn code_actions(
1768        &self,
1769        buffer: &Entity<Buffer>,
1770        range: Range<text::Anchor>,
1771        _: &mut Window,
1772        cx: &mut App,
1773    ) -> Task<Result<Vec<CodeAction>>> {
1774        if !AgentSettings::get_global(cx).enabled {
1775            return Task::ready(Ok(Vec::new()));
1776        }
1777
1778        let snapshot = buffer.read(cx).snapshot();
1779        let mut range = range.to_point(&snapshot);
1780
1781        // Expand the range to line boundaries.
1782        range.start.column = 0;
1783        range.end.column = snapshot.line_len(range.end.row);
1784
1785        let mut has_diagnostics = false;
1786        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1787            range.start = cmp::min(range.start, diagnostic.range.start);
1788            range.end = cmp::max(range.end, diagnostic.range.end);
1789            has_diagnostics = true;
1790        }
1791        if has_diagnostics {
1792            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
1793                if let Some(symbol) = symbols_containing_start.last() {
1794                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1795                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1796                }
1797            }
1798
1799            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
1800                if let Some(symbol) = symbols_containing_end.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            Task::ready(Ok(vec![CodeAction {
1807                server_id: language::LanguageServerId(0),
1808                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1809                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1810                    title: "Fix with Assistant".into(),
1811                    ..Default::default()
1812                })),
1813                resolved: true,
1814            }]))
1815        } else {
1816            Task::ready(Ok(Vec::new()))
1817        }
1818    }
1819
1820    fn apply_code_action(
1821        &self,
1822        buffer: Entity<Buffer>,
1823        action: CodeAction,
1824        excerpt_id: ExcerptId,
1825        _push_to_history: bool,
1826        window: &mut Window,
1827        cx: &mut App,
1828    ) -> Task<Result<ProjectTransaction>> {
1829        let editor = self.editor.clone();
1830        let workspace = self.workspace.clone();
1831        let thread_store = self.thread_store.clone();
1832        let text_thread_store = self.text_thread_store.clone();
1833        let prompt_store = PromptStore::global(cx);
1834        window.spawn(cx, async move |cx| {
1835            let workspace = workspace.upgrade().context("workspace was released")?;
1836            let editor = editor.upgrade().context("editor was released")?;
1837            let range = editor
1838                .update(cx, |editor, cx| {
1839                    editor.buffer().update(cx, |multibuffer, cx| {
1840                        let buffer = buffer.read(cx);
1841                        let multibuffer_snapshot = multibuffer.read(cx);
1842
1843                        let old_context_range =
1844                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1845                        let mut new_context_range = old_context_range.clone();
1846                        if action
1847                            .range
1848                            .start
1849                            .cmp(&old_context_range.start, buffer)
1850                            .is_lt()
1851                        {
1852                            new_context_range.start = action.range.start;
1853                        }
1854                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1855                            new_context_range.end = action.range.end;
1856                        }
1857                        drop(multibuffer_snapshot);
1858
1859                        if new_context_range != old_context_range {
1860                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1861                        }
1862
1863                        let multibuffer_snapshot = multibuffer.read(cx);
1864                        Some(
1865                            multibuffer_snapshot
1866                                .anchor_in_excerpt(excerpt_id, action.range.start)?
1867                                ..multibuffer_snapshot
1868                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
1869                        )
1870                    })
1871                })?
1872                .context("invalid range")?;
1873
1874            let prompt_store = prompt_store.await.ok();
1875            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1876                let assist_id = assistant.suggest_assist(
1877                    &editor,
1878                    range,
1879                    "Fix Diagnostics".into(),
1880                    None,
1881                    true,
1882                    workspace,
1883                    prompt_store,
1884                    thread_store,
1885                    text_thread_store,
1886                    window,
1887                    cx,
1888                );
1889                assistant.start_assist(assist_id, window, cx);
1890            })?;
1891
1892            Ok(ProjectTransaction::default())
1893        })
1894    }
1895}
1896
1897fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1898    ranges.sort_unstable_by(|a, b| {
1899        a.start
1900            .cmp(&b.start, buffer)
1901            .then_with(|| b.end.cmp(&a.end, buffer))
1902    });
1903
1904    let mut ix = 0;
1905    while ix + 1 < ranges.len() {
1906        let b = ranges[ix + 1].clone();
1907        let a = &mut ranges[ix];
1908        if a.end.cmp(&b.start, buffer).is_gt() {
1909            if a.end.cmp(&b.end, buffer).is_lt() {
1910                a.end = b.end;
1911            }
1912            ranges.remove(ix + 1);
1913        } else {
1914            ix += 1;
1915        }
1916    }
1917}