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