inline_assistant.rs

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