inline_assistant.rs

   1use crate::context::attach_context_to_message;
   2use crate::context_picker::ContextPicker;
   3use crate::context_store::ContextStore;
   4use crate::context_strip::ContextStrip;
   5use crate::thread_store::ThreadStore;
   6use crate::{
   7    assistant_settings::AssistantSettings,
   8    prompts::PromptBuilder,
   9    streaming_diff::{CharOperation, LineDiff, LineOperation, StreamingDiff},
  10    terminal_inline_assistant::TerminalInlineAssistant,
  11    CycleNextInlineAssist, CyclePreviousInlineAssist,
  12};
  13use crate::{AssistantPanel, ToggleContextPicker};
  14use anyhow::{Context as _, Result};
  15use client::{telemetry::Telemetry, ErrorExt};
  16use collections::{hash_map, HashMap, HashSet, VecDeque};
  17use editor::{
  18    actions::{MoveDown, MoveUp, SelectAll},
  19    display_map::{
  20        BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock,
  21        ToDisplayPoint,
  22    },
  23    Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorElement, EditorEvent, EditorMode,
  24    EditorStyle, ExcerptId, ExcerptRange, GutterDimensions, MultiBuffer, MultiBufferSnapshot,
  25    ToOffset as _, ToPoint,
  26};
  27use feature_flags::{FeatureFlagAppExt as _, ZedPro};
  28use fs::Fs;
  29use futures::{channel::mpsc, future::LocalBoxFuture, join, SinkExt, Stream, StreamExt};
  30use gpui::{
  31    anchored, deferred, point, AnyElement, AppContext, ClickEvent, CursorStyle, EventEmitter,
  32    FocusHandle, FocusableView, FontWeight, Global, HighlightStyle, Model, ModelContext,
  33    Subscription, Task, TextStyle, UpdateGlobal, View, ViewContext, WeakModel, WeakView,
  34    WindowContext,
  35};
  36use language::{Buffer, IndentKind, Point, Selection, TransactionId};
  37use language_model::{
  38    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
  39    LanguageModelTextStream, Role,
  40};
  41use language_model_selector::{LanguageModelSelector, LanguageModelSelectorPopoverMenu};
  42use language_models::report_assistant_event;
  43use multi_buffer::MultiBufferRow;
  44use parking_lot::Mutex;
  45use project::{CodeAction, ProjectTransaction};
  46use rope::Rope;
  47use settings::{update_settings_file, Settings, SettingsStore};
  48use smol::future::FutureExt;
  49use std::{
  50    cmp,
  51    future::Future,
  52    iter, mem,
  53    ops::{Range, RangeInclusive},
  54    pin::Pin,
  55    rc::Rc,
  56    sync::Arc,
  57    task::{self, Poll},
  58    time::Instant,
  59};
  60use telemetry_events::{AssistantEvent, AssistantKind, AssistantPhase};
  61use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
  62use text::{OffsetRangeExt, ToPoint as _};
  63use theme::ThemeSettings;
  64use ui::{
  65    prelude::*, CheckboxWithLabel, IconButtonShape, KeyBinding, Popover, PopoverMenuHandle, Tooltip,
  66};
  67use util::{RangeExt, ResultExt};
  68use workspace::{dock::Panel, ShowConfiguration};
  69use workspace::{notifications::NotificationId, ItemHandle, Toast, Workspace};
  70
  71pub fn init(
  72    fs: Arc<dyn Fs>,
  73    prompt_builder: Arc<PromptBuilder>,
  74    telemetry: Arc<Telemetry>,
  75    cx: &mut AppContext,
  76) {
  77    cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));
  78    cx.observe_new_views(|_workspace: &mut Workspace, cx| {
  79        let workspace = cx.view().clone();
  80        InlineAssistant::update_global(cx, |inline_assistant, cx| {
  81            inline_assistant.register_workspace(&workspace, cx)
  82        })
  83    })
  84    .detach();
  85}
  86
  87const PROMPT_HISTORY_MAX_LEN: usize = 20;
  88
  89enum InlineAssistTarget {
  90    Editor(View<Editor>),
  91    Terminal(View<TerminalView>),
  92}
  93
  94pub struct InlineAssistant {
  95    next_assist_id: InlineAssistId,
  96    next_assist_group_id: InlineAssistGroupId,
  97    assists: HashMap<InlineAssistId, InlineAssist>,
  98    assists_by_editor: HashMap<WeakView<Editor>, EditorInlineAssists>,
  99    assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,
 100    confirmed_assists: HashMap<InlineAssistId, Model<CodegenAlternative>>,
 101    prompt_history: VecDeque<String>,
 102    prompt_builder: Arc<PromptBuilder>,
 103    telemetry: Arc<Telemetry>,
 104    fs: Arc<dyn Fs>,
 105}
 106
 107impl Global for InlineAssistant {}
 108
 109impl InlineAssistant {
 110    pub fn new(
 111        fs: Arc<dyn Fs>,
 112        prompt_builder: Arc<PromptBuilder>,
 113        telemetry: Arc<Telemetry>,
 114    ) -> Self {
 115        Self {
 116            next_assist_id: InlineAssistId::default(),
 117            next_assist_group_id: InlineAssistGroupId::default(),
 118            assists: HashMap::default(),
 119            assists_by_editor: HashMap::default(),
 120            assist_groups: HashMap::default(),
 121            confirmed_assists: HashMap::default(),
 122            prompt_history: VecDeque::default(),
 123            prompt_builder,
 124            telemetry,
 125            fs,
 126        }
 127    }
 128
 129    pub fn register_workspace(&mut self, workspace: &View<Workspace>, cx: &mut WindowContext) {
 130        cx.subscribe(workspace, |workspace, event, cx| {
 131            Self::update_global(cx, |this, cx| {
 132                this.handle_workspace_event(workspace, event, cx)
 133            });
 134        })
 135        .detach();
 136
 137        let workspace = workspace.downgrade();
 138        cx.observe_global::<SettingsStore>(move |cx| {
 139            let Some(workspace) = workspace.upgrade() else {
 140                return;
 141            };
 142            let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
 143                return;
 144            };
 145            let enabled = AssistantSettings::get_global(cx).enabled;
 146            terminal_panel.update(cx, |terminal_panel, cx| {
 147                terminal_panel.asssistant_enabled(enabled, cx)
 148            });
 149        })
 150        .detach();
 151    }
 152
 153    fn handle_workspace_event(
 154        &mut self,
 155        workspace: View<Workspace>,
 156        event: &workspace::Event,
 157        cx: &mut WindowContext,
 158    ) {
 159        match event {
 160            workspace::Event::UserSavedItem { item, .. } => {
 161                // When the user manually saves an editor, automatically accepts all finished transformations.
 162                if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx)) {
 163                    if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 164                        for assist_id in editor_assists.assist_ids.clone() {
 165                            let assist = &self.assists[&assist_id];
 166                            if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
 167                                self.finish_assist(assist_id, false, cx)
 168                            }
 169                        }
 170                    }
 171                }
 172            }
 173            workspace::Event::ItemAdded { item } => {
 174                self.register_workspace_item(&workspace, item.as_ref(), cx);
 175            }
 176            _ => (),
 177        }
 178    }
 179
 180    fn register_workspace_item(
 181        &mut self,
 182        workspace: &View<Workspace>,
 183        item: &dyn ItemHandle,
 184        cx: &mut WindowContext,
 185    ) {
 186        if let Some(editor) = item.act_as::<Editor>(cx) {
 187            editor.update(cx, |editor, cx| {
 188                let thread_store = workspace
 189                    .read(cx)
 190                    .panel::<AssistantPanel>(cx)
 191                    .map(|assistant_panel| assistant_panel.read(cx).thread_store().downgrade());
 192
 193                editor.push_code_action_provider(
 194                    Rc::new(AssistantCodeActionProvider {
 195                        editor: cx.view().downgrade(),
 196                        workspace: workspace.downgrade(),
 197                        thread_store,
 198                    }),
 199                    cx,
 200                );
 201            });
 202        }
 203    }
 204
 205    pub fn inline_assist(
 206        workspace: &mut Workspace,
 207        _action: &zed_actions::InlineAssist,
 208        cx: &mut ViewContext<Workspace>,
 209    ) {
 210        let settings = AssistantSettings::get_global(cx);
 211        if !settings.enabled {
 212            return;
 213        }
 214
 215        let Some(inline_assist_target) = Self::resolve_inline_assist_target(workspace, cx) else {
 216            return;
 217        };
 218
 219        let is_authenticated = || {
 220            LanguageModelRegistry::read_global(cx)
 221                .active_provider()
 222                .map_or(false, |provider| provider.is_authenticated(cx))
 223        };
 224
 225        let thread_store = workspace
 226            .panel::<AssistantPanel>(cx)
 227            .map(|assistant_panel| assistant_panel.read(cx).thread_store().downgrade());
 228
 229        let handle_assist = |cx: &mut ViewContext<Workspace>| match inline_assist_target {
 230            InlineAssistTarget::Editor(active_editor) => {
 231                InlineAssistant::update_global(cx, |assistant, cx| {
 232                    assistant.assist(&active_editor, cx.view().downgrade(), thread_store, cx)
 233                })
 234            }
 235            InlineAssistTarget::Terminal(active_terminal) => {
 236                TerminalInlineAssistant::update_global(cx, |assistant, cx| {
 237                    assistant.assist(&active_terminal, cx.view().downgrade(), thread_store, cx)
 238                })
 239            }
 240        };
 241
 242        if is_authenticated() {
 243            handle_assist(cx);
 244        } else {
 245            cx.spawn(|_workspace, mut cx| async move {
 246                let Some(task) = cx.update(|cx| {
 247                    LanguageModelRegistry::read_global(cx)
 248                        .active_provider()
 249                        .map_or(None, |provider| Some(provider.authenticate(cx)))
 250                })?
 251                else {
 252                    let answer = cx
 253                        .prompt(
 254                            gpui::PromptLevel::Warning,
 255                            "No language model provider configured",
 256                            None,
 257                            &["Configure", "Cancel"],
 258                        )
 259                        .await
 260                        .ok();
 261                    if let Some(answer) = answer {
 262                        if answer == 0 {
 263                            cx.update(|cx| cx.dispatch_action(Box::new(ShowConfiguration)))
 264                                .ok();
 265                        }
 266                    }
 267                    return Ok(());
 268                };
 269                task.await?;
 270
 271                anyhow::Ok(())
 272            })
 273            .detach_and_log_err(cx);
 274
 275            if is_authenticated() {
 276                handle_assist(cx);
 277            }
 278        }
 279    }
 280
 281    pub fn assist(
 282        &mut self,
 283        editor: &View<Editor>,
 284        workspace: WeakView<Workspace>,
 285        thread_store: Option<WeakModel<ThreadStore>>,
 286        cx: &mut WindowContext,
 287    ) {
 288        let (snapshot, initial_selections) = editor.update(cx, |editor, cx| {
 289            (
 290                editor.buffer().read(cx).snapshot(cx),
 291                editor.selections.all::<Point>(cx),
 292            )
 293        });
 294
 295        let mut selections = Vec::<Selection<Point>>::new();
 296        let mut newest_selection = None;
 297        for mut selection in initial_selections {
 298            if selection.end > selection.start {
 299                selection.start.column = 0;
 300                // If the selection ends at the start of the line, we don't want to include it.
 301                if selection.end.column == 0 {
 302                    selection.end.row -= 1;
 303                }
 304                selection.end.column = snapshot.line_len(MultiBufferRow(selection.end.row));
 305            }
 306
 307            if let Some(prev_selection) = selections.last_mut() {
 308                if selection.start <= prev_selection.end {
 309                    prev_selection.end = selection.end;
 310                    continue;
 311                }
 312            }
 313
 314            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 315            if selection.id > latest_selection.id {
 316                *latest_selection = selection.clone();
 317            }
 318            selections.push(selection);
 319        }
 320        let newest_selection = newest_selection.unwrap();
 321
 322        let mut codegen_ranges = Vec::new();
 323        for (excerpt_id, buffer, buffer_range) in
 324            snapshot.excerpts_in_ranges(selections.iter().map(|selection| {
 325                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 326            }))
 327        {
 328            let start = Anchor {
 329                buffer_id: Some(buffer.remote_id()),
 330                excerpt_id,
 331                text_anchor: buffer.anchor_before(buffer_range.start),
 332            };
 333            let end = Anchor {
 334                buffer_id: Some(buffer.remote_id()),
 335                excerpt_id,
 336                text_anchor: buffer.anchor_after(buffer_range.end),
 337            };
 338            codegen_ranges.push(start..end);
 339
 340            if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
 341                self.telemetry.report_assistant_event(AssistantEvent {
 342                    conversation_id: None,
 343                    kind: AssistantKind::Inline,
 344                    phase: AssistantPhase::Invoked,
 345                    message_id: None,
 346                    model: model.telemetry_id(),
 347                    model_provider: model.provider_id().to_string(),
 348                    response_latency: None,
 349                    error_message: None,
 350                    language_name: buffer.language().map(|language| language.name().to_proto()),
 351                });
 352            }
 353        }
 354
 355        let assist_group_id = self.next_assist_group_id.post_inc();
 356        let prompt_buffer = cx.new_model(|cx| {
 357            MultiBuffer::singleton(cx.new_model(|cx| Buffer::local(String::new(), cx)), cx)
 358        });
 359
 360        let mut assists = Vec::new();
 361        let mut assist_to_focus = None;
 362        for range in codegen_ranges {
 363            let assist_id = self.next_assist_id.post_inc();
 364            let context_store = cx.new_model(|_cx| ContextStore::new());
 365            let codegen = cx.new_model(|cx| {
 366                Codegen::new(
 367                    editor.read(cx).buffer().clone(),
 368                    range.clone(),
 369                    None,
 370                    context_store.clone(),
 371                    self.telemetry.clone(),
 372                    self.prompt_builder.clone(),
 373                    cx,
 374                )
 375            });
 376
 377            let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
 378            let prompt_editor = cx.new_view(|cx| {
 379                PromptEditor::new(
 380                    assist_id,
 381                    gutter_dimensions.clone(),
 382                    self.prompt_history.clone(),
 383                    prompt_buffer.clone(),
 384                    codegen.clone(),
 385                    self.fs.clone(),
 386                    context_store,
 387                    workspace.clone(),
 388                    thread_store.clone(),
 389                    cx,
 390                )
 391            });
 392
 393            if assist_to_focus.is_none() {
 394                let focus_assist = if newest_selection.reversed {
 395                    range.start.to_point(&snapshot) == newest_selection.start
 396                } else {
 397                    range.end.to_point(&snapshot) == newest_selection.end
 398                };
 399                if focus_assist {
 400                    assist_to_focus = Some(assist_id);
 401                }
 402            }
 403
 404            let [prompt_block_id, end_block_id] =
 405                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 406
 407            assists.push((
 408                assist_id,
 409                range,
 410                prompt_editor,
 411                prompt_block_id,
 412                end_block_id,
 413            ));
 414        }
 415
 416        let editor_assists = self
 417            .assists_by_editor
 418            .entry(editor.downgrade())
 419            .or_insert_with(|| EditorInlineAssists::new(&editor, cx));
 420        let mut assist_group = InlineAssistGroup::new();
 421        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
 422            self.assists.insert(
 423                assist_id,
 424                InlineAssist::new(
 425                    assist_id,
 426                    assist_group_id,
 427                    editor,
 428                    &prompt_editor,
 429                    prompt_block_id,
 430                    end_block_id,
 431                    range,
 432                    prompt_editor.read(cx).codegen.clone(),
 433                    workspace.clone(),
 434                    cx,
 435                ),
 436            );
 437            assist_group.assist_ids.push(assist_id);
 438            editor_assists.assist_ids.push(assist_id);
 439        }
 440        self.assist_groups.insert(assist_group_id, assist_group);
 441
 442        if let Some(assist_id) = assist_to_focus {
 443            self.focus_assist(assist_id, cx);
 444        }
 445    }
 446
 447    #[allow(clippy::too_many_arguments)]
 448    pub fn suggest_assist(
 449        &mut self,
 450        editor: &View<Editor>,
 451        mut range: Range<Anchor>,
 452        initial_prompt: String,
 453        initial_transaction_id: Option<TransactionId>,
 454        focus: bool,
 455        workspace: WeakView<Workspace>,
 456        thread_store: Option<WeakModel<ThreadStore>>,
 457        cx: &mut WindowContext,
 458    ) -> InlineAssistId {
 459        let assist_group_id = self.next_assist_group_id.post_inc();
 460        let prompt_buffer = cx.new_model(|cx| Buffer::local(&initial_prompt, cx));
 461        let prompt_buffer = cx.new_model(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 462
 463        let assist_id = self.next_assist_id.post_inc();
 464
 465        let buffer = editor.read(cx).buffer().clone();
 466        {
 467            let snapshot = buffer.read(cx).read(cx);
 468            range.start = range.start.bias_left(&snapshot);
 469            range.end = range.end.bias_right(&snapshot);
 470        }
 471
 472        let context_store = cx.new_model(|_cx| ContextStore::new());
 473
 474        let codegen = cx.new_model(|cx| {
 475            Codegen::new(
 476                editor.read(cx).buffer().clone(),
 477                range.clone(),
 478                initial_transaction_id,
 479                context_store.clone(),
 480                self.telemetry.clone(),
 481                self.prompt_builder.clone(),
 482                cx,
 483            )
 484        });
 485
 486        let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
 487        let prompt_editor = cx.new_view(|cx| {
 488            PromptEditor::new(
 489                assist_id,
 490                gutter_dimensions.clone(),
 491                self.prompt_history.clone(),
 492                prompt_buffer.clone(),
 493                codegen.clone(),
 494                self.fs.clone(),
 495                context_store,
 496                workspace.clone(),
 497                thread_store,
 498                cx,
 499            )
 500        });
 501
 502        let [prompt_block_id, end_block_id] =
 503            self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 504
 505        let editor_assists = self
 506            .assists_by_editor
 507            .entry(editor.downgrade())
 508            .or_insert_with(|| EditorInlineAssists::new(&editor, cx));
 509
 510        let mut assist_group = InlineAssistGroup::new();
 511        self.assists.insert(
 512            assist_id,
 513            InlineAssist::new(
 514                assist_id,
 515                assist_group_id,
 516                editor,
 517                &prompt_editor,
 518                prompt_block_id,
 519                end_block_id,
 520                range,
 521                prompt_editor.read(cx).codegen.clone(),
 522                workspace.clone(),
 523                cx,
 524            ),
 525        );
 526        assist_group.assist_ids.push(assist_id);
 527        editor_assists.assist_ids.push(assist_id);
 528        self.assist_groups.insert(assist_group_id, assist_group);
 529
 530        if focus {
 531            self.focus_assist(assist_id, cx);
 532        }
 533
 534        assist_id
 535    }
 536
 537    fn insert_assist_blocks(
 538        &self,
 539        editor: &View<Editor>,
 540        range: &Range<Anchor>,
 541        prompt_editor: &View<PromptEditor>,
 542        cx: &mut WindowContext,
 543    ) -> [CustomBlockId; 2] {
 544        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 545            prompt_editor
 546                .editor
 547                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 548        });
 549        let assist_blocks = vec![
 550            BlockProperties {
 551                style: BlockStyle::Sticky,
 552                placement: BlockPlacement::Above(range.start),
 553                height: prompt_editor_height,
 554                render: build_assist_editor_renderer(prompt_editor),
 555                priority: 0,
 556            },
 557            BlockProperties {
 558                style: BlockStyle::Sticky,
 559                placement: BlockPlacement::Below(range.end),
 560                height: 0,
 561                render: Arc::new(|cx| {
 562                    v_flex()
 563                        .h_full()
 564                        .w_full()
 565                        .border_t_1()
 566                        .border_color(cx.theme().status().info_border)
 567                        .into_any_element()
 568                }),
 569                priority: 0,
 570            },
 571        ];
 572
 573        editor.update(cx, |editor, cx| {
 574            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 575            [block_ids[0], block_ids[1]]
 576        })
 577    }
 578
 579    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
 580        let assist = &self.assists[&assist_id];
 581        let Some(decorations) = assist.decorations.as_ref() else {
 582            return;
 583        };
 584        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 585        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 586
 587        assist_group.active_assist_id = Some(assist_id);
 588        if assist_group.linked {
 589            for assist_id in &assist_group.assist_ids {
 590                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 591                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 592                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 593                    });
 594                }
 595            }
 596        }
 597
 598        assist
 599            .editor
 600            .update(cx, |editor, cx| {
 601                let scroll_top = editor.scroll_position(cx).y;
 602                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 603                let prompt_row = editor
 604                    .row_for_block(decorations.prompt_block_id, cx)
 605                    .unwrap()
 606                    .0 as f32;
 607
 608                if (scroll_top..scroll_bottom).contains(&prompt_row) {
 609                    editor_assists.scroll_lock = Some(InlineAssistScrollLock {
 610                        assist_id,
 611                        distance_from_top: prompt_row - scroll_top,
 612                    });
 613                } else {
 614                    editor_assists.scroll_lock = None;
 615                }
 616            })
 617            .ok();
 618    }
 619
 620    fn handle_prompt_editor_focus_out(
 621        &mut self,
 622        assist_id: InlineAssistId,
 623        cx: &mut WindowContext,
 624    ) {
 625        let assist = &self.assists[&assist_id];
 626        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 627        if assist_group.active_assist_id == Some(assist_id) {
 628            assist_group.active_assist_id = None;
 629            if assist_group.linked {
 630                for assist_id in &assist_group.assist_ids {
 631                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 632                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 633                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 634                        });
 635                    }
 636                }
 637            }
 638        }
 639    }
 640
 641    fn handle_prompt_editor_event(
 642        &mut self,
 643        prompt_editor: View<PromptEditor>,
 644        event: &PromptEditorEvent,
 645        cx: &mut WindowContext,
 646    ) {
 647        let assist_id = prompt_editor.read(cx).id;
 648        match event {
 649            PromptEditorEvent::StartRequested => {
 650                self.start_assist(assist_id, cx);
 651            }
 652            PromptEditorEvent::StopRequested => {
 653                self.stop_assist(assist_id, cx);
 654            }
 655            PromptEditorEvent::ConfirmRequested => {
 656                self.finish_assist(assist_id, false, cx);
 657            }
 658            PromptEditorEvent::CancelRequested => {
 659                self.finish_assist(assist_id, true, cx);
 660            }
 661            PromptEditorEvent::DismissRequested => {
 662                self.dismiss_assist(assist_id, cx);
 663            }
 664        }
 665    }
 666
 667    fn handle_editor_newline(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
 668        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 669            return;
 670        };
 671
 672        if editor.read(cx).selections.count() == 1 {
 673            let (selection, buffer) = editor.update(cx, |editor, cx| {
 674                (
 675                    editor.selections.newest::<usize>(cx),
 676                    editor.buffer().read(cx).snapshot(cx),
 677                )
 678            });
 679            for assist_id in &editor_assists.assist_ids {
 680                let assist = &self.assists[assist_id];
 681                let assist_range = assist.range.to_offset(&buffer);
 682                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 683                {
 684                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 685                        self.dismiss_assist(*assist_id, cx);
 686                    } else {
 687                        self.finish_assist(*assist_id, false, cx);
 688                    }
 689
 690                    return;
 691                }
 692            }
 693        }
 694
 695        cx.propagate();
 696    }
 697
 698    fn handle_editor_cancel(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
 699        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 700            return;
 701        };
 702
 703        if editor.read(cx).selections.count() == 1 {
 704            let (selection, buffer) = editor.update(cx, |editor, cx| {
 705                (
 706                    editor.selections.newest::<usize>(cx),
 707                    editor.buffer().read(cx).snapshot(cx),
 708                )
 709            });
 710            let mut closest_assist_fallback = None;
 711            for assist_id in &editor_assists.assist_ids {
 712                let assist = &self.assists[assist_id];
 713                let assist_range = assist.range.to_offset(&buffer);
 714                if assist.decorations.is_some() {
 715                    if assist_range.contains(&selection.start)
 716                        && assist_range.contains(&selection.end)
 717                    {
 718                        self.focus_assist(*assist_id, cx);
 719                        return;
 720                    } else {
 721                        let distance_from_selection = assist_range
 722                            .start
 723                            .abs_diff(selection.start)
 724                            .min(assist_range.start.abs_diff(selection.end))
 725                            + assist_range
 726                                .end
 727                                .abs_diff(selection.start)
 728                                .min(assist_range.end.abs_diff(selection.end));
 729                        match closest_assist_fallback {
 730                            Some((_, old_distance)) => {
 731                                if distance_from_selection < old_distance {
 732                                    closest_assist_fallback =
 733                                        Some((assist_id, distance_from_selection));
 734                                }
 735                            }
 736                            None => {
 737                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 738                            }
 739                        }
 740                    }
 741                }
 742            }
 743
 744            if let Some((&assist_id, _)) = closest_assist_fallback {
 745                self.focus_assist(assist_id, cx);
 746            }
 747        }
 748
 749        cx.propagate();
 750    }
 751
 752    fn handle_editor_release(&mut self, editor: WeakView<Editor>, cx: &mut WindowContext) {
 753        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 754            for assist_id in editor_assists.assist_ids.clone() {
 755                self.finish_assist(assist_id, true, cx);
 756            }
 757        }
 758    }
 759
 760    fn handle_editor_change(&mut self, editor: View<Editor>, cx: &mut WindowContext) {
 761        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 762            return;
 763        };
 764        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 765            return;
 766        };
 767        let assist = &self.assists[&scroll_lock.assist_id];
 768        let Some(decorations) = assist.decorations.as_ref() else {
 769            return;
 770        };
 771
 772        editor.update(cx, |editor, cx| {
 773            let scroll_position = editor.scroll_position(cx);
 774            let target_scroll_top = editor
 775                .row_for_block(decorations.prompt_block_id, cx)
 776                .unwrap()
 777                .0 as f32
 778                - scroll_lock.distance_from_top;
 779            if target_scroll_top != scroll_position.y {
 780                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), cx);
 781            }
 782        });
 783    }
 784
 785    fn handle_editor_event(
 786        &mut self,
 787        editor: View<Editor>,
 788        event: &EditorEvent,
 789        cx: &mut WindowContext,
 790    ) {
 791        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 792            return;
 793        };
 794
 795        match event {
 796            EditorEvent::Edited { transaction_id } => {
 797                let buffer = editor.read(cx).buffer().read(cx);
 798                let edited_ranges =
 799                    buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
 800                let snapshot = buffer.snapshot(cx);
 801
 802                for assist_id in editor_assists.assist_ids.clone() {
 803                    let assist = &self.assists[&assist_id];
 804                    if matches!(
 805                        assist.codegen.read(cx).status(cx),
 806                        CodegenStatus::Error(_) | CodegenStatus::Done
 807                    ) {
 808                        let assist_range = assist.range.to_offset(&snapshot);
 809                        if edited_ranges
 810                            .iter()
 811                            .any(|range| range.overlaps(&assist_range))
 812                        {
 813                            self.finish_assist(assist_id, false, cx);
 814                        }
 815                    }
 816                }
 817            }
 818            EditorEvent::ScrollPositionChanged { .. } => {
 819                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 820                    let assist = &self.assists[&scroll_lock.assist_id];
 821                    if let Some(decorations) = assist.decorations.as_ref() {
 822                        let distance_from_top = editor.update(cx, |editor, cx| {
 823                            let scroll_top = editor.scroll_position(cx).y;
 824                            let prompt_row = editor
 825                                .row_for_block(decorations.prompt_block_id, cx)
 826                                .unwrap()
 827                                .0 as f32;
 828                            prompt_row - scroll_top
 829                        });
 830
 831                        if distance_from_top != scroll_lock.distance_from_top {
 832                            editor_assists.scroll_lock = None;
 833                        }
 834                    }
 835                }
 836            }
 837            EditorEvent::SelectionsChanged { .. } => {
 838                for assist_id in editor_assists.assist_ids.clone() {
 839                    let assist = &self.assists[&assist_id];
 840                    if let Some(decorations) = assist.decorations.as_ref() {
 841                        if decorations.prompt_editor.focus_handle(cx).is_focused(cx) {
 842                            return;
 843                        }
 844                    }
 845                }
 846
 847                editor_assists.scroll_lock = None;
 848            }
 849            _ => {}
 850        }
 851    }
 852
 853    pub fn finish_assist(&mut self, assist_id: InlineAssistId, undo: bool, cx: &mut WindowContext) {
 854        if let Some(assist) = self.assists.get(&assist_id) {
 855            let assist_group_id = assist.group_id;
 856            if self.assist_groups[&assist_group_id].linked {
 857                for assist_id in self.unlink_assist_group(assist_group_id, cx) {
 858                    self.finish_assist(assist_id, undo, cx);
 859                }
 860                return;
 861            }
 862        }
 863
 864        self.dismiss_assist(assist_id, cx);
 865
 866        if let Some(assist) = self.assists.remove(&assist_id) {
 867            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
 868            {
 869                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 870                if entry.get().assist_ids.is_empty() {
 871                    entry.remove();
 872                }
 873            }
 874
 875            if let hash_map::Entry::Occupied(mut entry) =
 876                self.assists_by_editor.entry(assist.editor.clone())
 877            {
 878                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 879                if entry.get().assist_ids.is_empty() {
 880                    entry.remove();
 881                    if let Some(editor) = assist.editor.upgrade() {
 882                        self.update_editor_highlights(&editor, cx);
 883                    }
 884                } else {
 885                    entry.get().highlight_updates.send(()).ok();
 886                }
 887            }
 888
 889            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
 890            let message_id = active_alternative.read(cx).message_id.clone();
 891
 892            if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
 893                let language_name = assist.editor.upgrade().and_then(|editor| {
 894                    let multibuffer = editor.read(cx).buffer().read(cx);
 895                    let ranges = multibuffer.range_to_buffer_ranges(assist.range.clone(), cx);
 896                    ranges
 897                        .first()
 898                        .and_then(|(buffer, _, _)| buffer.read(cx).language())
 899                        .map(|language| language.name())
 900                });
 901                report_assistant_event(
 902                    AssistantEvent {
 903                        conversation_id: None,
 904                        kind: AssistantKind::Inline,
 905                        message_id,
 906                        phase: if undo {
 907                            AssistantPhase::Rejected
 908                        } else {
 909                            AssistantPhase::Accepted
 910                        },
 911                        model: model.telemetry_id(),
 912                        model_provider: model.provider_id().to_string(),
 913                        response_latency: None,
 914                        error_message: None,
 915                        language_name: language_name.map(|name| name.to_proto()),
 916                    },
 917                    Some(self.telemetry.clone()),
 918                    cx.http_client(),
 919                    model.api_key(cx),
 920                    cx.background_executor(),
 921                );
 922            }
 923
 924            if undo {
 925                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
 926            } else {
 927                self.confirmed_assists.insert(assist_id, active_alternative);
 928            }
 929        }
 930    }
 931
 932    fn dismiss_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) -> bool {
 933        let Some(assist) = self.assists.get_mut(&assist_id) else {
 934            return false;
 935        };
 936        let Some(editor) = assist.editor.upgrade() else {
 937            return false;
 938        };
 939        let Some(decorations) = assist.decorations.take() else {
 940            return false;
 941        };
 942
 943        editor.update(cx, |editor, cx| {
 944            let mut to_remove = decorations.removed_line_block_ids;
 945            to_remove.insert(decorations.prompt_block_id);
 946            to_remove.insert(decorations.end_block_id);
 947            editor.remove_blocks(to_remove, None, cx);
 948        });
 949
 950        if decorations
 951            .prompt_editor
 952            .focus_handle(cx)
 953            .contains_focused(cx)
 954        {
 955            self.focus_next_assist(assist_id, cx);
 956        }
 957
 958        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
 959            if editor_assists
 960                .scroll_lock
 961                .as_ref()
 962                .map_or(false, |lock| lock.assist_id == assist_id)
 963            {
 964                editor_assists.scroll_lock = None;
 965            }
 966            editor_assists.highlight_updates.send(()).ok();
 967        }
 968
 969        true
 970    }
 971
 972    fn focus_next_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
 973        let Some(assist) = self.assists.get(&assist_id) else {
 974            return;
 975        };
 976
 977        let assist_group = &self.assist_groups[&assist.group_id];
 978        let assist_ix = assist_group
 979            .assist_ids
 980            .iter()
 981            .position(|id| *id == assist_id)
 982            .unwrap();
 983        let assist_ids = assist_group
 984            .assist_ids
 985            .iter()
 986            .skip(assist_ix + 1)
 987            .chain(assist_group.assist_ids.iter().take(assist_ix));
 988
 989        for assist_id in assist_ids {
 990            let assist = &self.assists[assist_id];
 991            if assist.decorations.is_some() {
 992                self.focus_assist(*assist_id, cx);
 993                return;
 994            }
 995        }
 996
 997        assist.editor.update(cx, |editor, cx| editor.focus(cx)).ok();
 998    }
 999
1000    fn focus_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
1001        let Some(assist) = self.assists.get(&assist_id) else {
1002            return;
1003        };
1004
1005        if let Some(decorations) = assist.decorations.as_ref() {
1006            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1007                prompt_editor.editor.update(cx, |editor, cx| {
1008                    editor.focus(cx);
1009                    editor.select_all(&SelectAll, cx);
1010                })
1011            });
1012        }
1013
1014        self.scroll_to_assist(assist_id, cx);
1015    }
1016
1017    pub fn scroll_to_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
1018        let Some(assist) = self.assists.get(&assist_id) else {
1019            return;
1020        };
1021        let Some(editor) = assist.editor.upgrade() else {
1022            return;
1023        };
1024
1025        let position = assist.range.start;
1026        editor.update(cx, |editor, cx| {
1027            editor.change_selections(None, cx, |selections| {
1028                selections.select_anchor_ranges([position..position])
1029            });
1030
1031            let mut scroll_target_top;
1032            let mut scroll_target_bottom;
1033            if let Some(decorations) = assist.decorations.as_ref() {
1034                scroll_target_top = editor
1035                    .row_for_block(decorations.prompt_block_id, cx)
1036                    .unwrap()
1037                    .0 as f32;
1038                scroll_target_bottom = editor
1039                    .row_for_block(decorations.end_block_id, cx)
1040                    .unwrap()
1041                    .0 as f32;
1042            } else {
1043                let snapshot = editor.snapshot(cx);
1044                let start_row = assist
1045                    .range
1046                    .start
1047                    .to_display_point(&snapshot.display_snapshot)
1048                    .row();
1049                scroll_target_top = start_row.0 as f32;
1050                scroll_target_bottom = scroll_target_top + 1.;
1051            }
1052            scroll_target_top -= editor.vertical_scroll_margin() as f32;
1053            scroll_target_bottom += editor.vertical_scroll_margin() as f32;
1054
1055            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1056            let scroll_top = editor.scroll_position(cx).y;
1057            let scroll_bottom = scroll_top + height_in_lines;
1058
1059            if scroll_target_top < scroll_top {
1060                editor.set_scroll_position(point(0., scroll_target_top), cx);
1061            } else if scroll_target_bottom > scroll_bottom {
1062                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1063                    editor
1064                        .set_scroll_position(point(0., scroll_target_bottom - height_in_lines), cx);
1065                } else {
1066                    editor.set_scroll_position(point(0., scroll_target_top), cx);
1067                }
1068            }
1069        });
1070    }
1071
1072    fn unlink_assist_group(
1073        &mut self,
1074        assist_group_id: InlineAssistGroupId,
1075        cx: &mut WindowContext,
1076    ) -> Vec<InlineAssistId> {
1077        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1078        assist_group.linked = false;
1079        for assist_id in &assist_group.assist_ids {
1080            let assist = self.assists.get_mut(assist_id).unwrap();
1081            if let Some(editor_decorations) = assist.decorations.as_ref() {
1082                editor_decorations
1083                    .prompt_editor
1084                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(cx));
1085            }
1086        }
1087        assist_group.assist_ids.clone()
1088    }
1089
1090    pub fn start_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
1091        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1092            assist
1093        } else {
1094            return;
1095        };
1096
1097        let assist_group_id = assist.group_id;
1098        if self.assist_groups[&assist_group_id].linked {
1099            for assist_id in self.unlink_assist_group(assist_group_id, cx) {
1100                self.start_assist(assist_id, cx);
1101            }
1102            return;
1103        }
1104
1105        let Some(user_prompt) = assist.user_prompt(cx) else {
1106            return;
1107        };
1108
1109        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1110        self.prompt_history.push_back(user_prompt.clone());
1111        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1112            self.prompt_history.pop_front();
1113        }
1114
1115        assist
1116            .codegen
1117            .update(cx, |codegen, cx| codegen.start(user_prompt, cx))
1118            .log_err();
1119    }
1120
1121    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
1122        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1123            assist
1124        } else {
1125            return;
1126        };
1127
1128        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1129    }
1130
1131    fn update_editor_highlights(&self, editor: &View<Editor>, cx: &mut WindowContext) {
1132        let mut gutter_pending_ranges = Vec::new();
1133        let mut gutter_transformed_ranges = Vec::new();
1134        let mut foreground_ranges = Vec::new();
1135        let mut inserted_row_ranges = Vec::new();
1136        let empty_assist_ids = Vec::new();
1137        let assist_ids = self
1138            .assists_by_editor
1139            .get(&editor.downgrade())
1140            .map_or(&empty_assist_ids, |editor_assists| {
1141                &editor_assists.assist_ids
1142            });
1143
1144        for assist_id in assist_ids {
1145            if let Some(assist) = self.assists.get(assist_id) {
1146                let codegen = assist.codegen.read(cx);
1147                let buffer = codegen.buffer(cx).read(cx).read(cx);
1148                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1149
1150                let pending_range =
1151                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1152                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1153                    gutter_pending_ranges.push(pending_range);
1154                }
1155
1156                if let Some(edit_position) = codegen.edit_position(cx) {
1157                    let edited_range = assist.range.start..edit_position;
1158                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1159                        gutter_transformed_ranges.push(edited_range);
1160                    }
1161                }
1162
1163                if assist.decorations.is_some() {
1164                    inserted_row_ranges
1165                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1166                }
1167            }
1168        }
1169
1170        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1171        merge_ranges(&mut foreground_ranges, &snapshot);
1172        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1173        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1174        editor.update(cx, |editor, cx| {
1175            enum GutterPendingRange {}
1176            if gutter_pending_ranges.is_empty() {
1177                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1178            } else {
1179                editor.highlight_gutter::<GutterPendingRange>(
1180                    &gutter_pending_ranges,
1181                    |cx| cx.theme().status().info_background,
1182                    cx,
1183                )
1184            }
1185
1186            enum GutterTransformedRange {}
1187            if gutter_transformed_ranges.is_empty() {
1188                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1189            } else {
1190                editor.highlight_gutter::<GutterTransformedRange>(
1191                    &gutter_transformed_ranges,
1192                    |cx| cx.theme().status().info,
1193                    cx,
1194                )
1195            }
1196
1197            if foreground_ranges.is_empty() {
1198                editor.clear_highlights::<InlineAssist>(cx);
1199            } else {
1200                editor.highlight_text::<InlineAssist>(
1201                    foreground_ranges,
1202                    HighlightStyle {
1203                        fade_out: Some(0.6),
1204                        ..Default::default()
1205                    },
1206                    cx,
1207                );
1208            }
1209
1210            editor.clear_row_highlights::<InlineAssist>();
1211            for row_range in inserted_row_ranges {
1212                editor.highlight_rows::<InlineAssist>(
1213                    row_range,
1214                    cx.theme().status().info_background,
1215                    false,
1216                    cx,
1217                );
1218            }
1219        });
1220    }
1221
1222    fn update_editor_blocks(
1223        &mut self,
1224        editor: &View<Editor>,
1225        assist_id: InlineAssistId,
1226        cx: &mut WindowContext,
1227    ) {
1228        let Some(assist) = self.assists.get_mut(&assist_id) else {
1229            return;
1230        };
1231        let Some(decorations) = assist.decorations.as_mut() else {
1232            return;
1233        };
1234
1235        let codegen = assist.codegen.read(cx);
1236        let old_snapshot = codegen.snapshot(cx);
1237        let old_buffer = codegen.old_buffer(cx);
1238        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1239
1240        editor.update(cx, |editor, cx| {
1241            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1242            editor.remove_blocks(old_blocks, None, cx);
1243
1244            let mut new_blocks = Vec::new();
1245            for (new_row, old_row_range) in deleted_row_ranges {
1246                let (_, buffer_start) = old_snapshot
1247                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1248                    .unwrap();
1249                let (_, buffer_end) = old_snapshot
1250                    .point_to_buffer_offset(Point::new(
1251                        *old_row_range.end(),
1252                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1253                    ))
1254                    .unwrap();
1255
1256                let deleted_lines_editor = cx.new_view(|cx| {
1257                    let multi_buffer = cx.new_model(|_| {
1258                        MultiBuffer::without_headers(language::Capability::ReadOnly)
1259                    });
1260                    multi_buffer.update(cx, |multi_buffer, cx| {
1261                        multi_buffer.push_excerpts(
1262                            old_buffer.clone(),
1263                            Some(ExcerptRange {
1264                                context: buffer_start..buffer_end,
1265                                primary: None,
1266                            }),
1267                            cx,
1268                        );
1269                    });
1270
1271                    enum DeletedLines {}
1272                    let mut editor = Editor::for_multibuffer(multi_buffer, None, true, cx);
1273                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1274                    editor.set_show_wrap_guides(false, cx);
1275                    editor.set_show_gutter(false, cx);
1276                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1277                    editor.set_read_only(true);
1278                    editor.set_show_inline_completions(Some(false), cx);
1279                    editor.highlight_rows::<DeletedLines>(
1280                        Anchor::min()..Anchor::max(),
1281                        cx.theme().status().deleted_background,
1282                        false,
1283                        cx,
1284                    );
1285                    editor
1286                });
1287
1288                let height =
1289                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1290                new_blocks.push(BlockProperties {
1291                    placement: BlockPlacement::Above(new_row),
1292                    height,
1293                    style: BlockStyle::Flex,
1294                    render: Arc::new(move |cx| {
1295                        div()
1296                            .block_mouse_down()
1297                            .bg(cx.theme().status().deleted_background)
1298                            .size_full()
1299                            .h(height as f32 * cx.line_height())
1300                            .pl(cx.gutter_dimensions.full_width())
1301                            .child(deleted_lines_editor.clone())
1302                            .into_any_element()
1303                    }),
1304                    priority: 0,
1305                });
1306            }
1307
1308            decorations.removed_line_block_ids = editor
1309                .insert_blocks(new_blocks, None, cx)
1310                .into_iter()
1311                .collect();
1312        })
1313    }
1314
1315    fn resolve_inline_assist_target(
1316        workspace: &mut Workspace,
1317        cx: &mut WindowContext,
1318    ) -> Option<InlineAssistTarget> {
1319        if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
1320            if terminal_panel
1321                .read(cx)
1322                .focus_handle(cx)
1323                .contains_focused(cx)
1324            {
1325                if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1326                    pane.read(cx)
1327                        .active_item()
1328                        .and_then(|t| t.downcast::<TerminalView>())
1329                }) {
1330                    return Some(InlineAssistTarget::Terminal(terminal_view));
1331                }
1332            }
1333        }
1334
1335        if let Some(workspace_editor) = workspace
1336            .active_item(cx)
1337            .and_then(|item| item.act_as::<Editor>(cx))
1338        {
1339            Some(InlineAssistTarget::Editor(workspace_editor))
1340        } else if let Some(terminal_view) = workspace
1341            .active_item(cx)
1342            .and_then(|item| item.act_as::<TerminalView>(cx))
1343        {
1344            Some(InlineAssistTarget::Terminal(terminal_view))
1345        } else {
1346            None
1347        }
1348    }
1349}
1350
1351struct EditorInlineAssists {
1352    assist_ids: Vec<InlineAssistId>,
1353    scroll_lock: Option<InlineAssistScrollLock>,
1354    highlight_updates: async_watch::Sender<()>,
1355    _update_highlights: Task<Result<()>>,
1356    _subscriptions: Vec<gpui::Subscription>,
1357}
1358
1359struct InlineAssistScrollLock {
1360    assist_id: InlineAssistId,
1361    distance_from_top: f32,
1362}
1363
1364impl EditorInlineAssists {
1365    #[allow(clippy::too_many_arguments)]
1366    fn new(editor: &View<Editor>, cx: &mut WindowContext) -> Self {
1367        let (highlight_updates_tx, mut highlight_updates_rx) = async_watch::channel(());
1368        Self {
1369            assist_ids: Vec::new(),
1370            scroll_lock: None,
1371            highlight_updates: highlight_updates_tx,
1372            _update_highlights: cx.spawn(|mut cx| {
1373                let editor = editor.downgrade();
1374                async move {
1375                    while let Ok(()) = highlight_updates_rx.changed().await {
1376                        let editor = editor.upgrade().context("editor was dropped")?;
1377                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1378                            assistant.update_editor_highlights(&editor, cx);
1379                        })?;
1380                    }
1381                    Ok(())
1382                }
1383            }),
1384            _subscriptions: vec![
1385                cx.observe_release(editor, {
1386                    let editor = editor.downgrade();
1387                    |_, cx| {
1388                        InlineAssistant::update_global(cx, |this, cx| {
1389                            this.handle_editor_release(editor, cx);
1390                        })
1391                    }
1392                }),
1393                cx.observe(editor, move |editor, cx| {
1394                    InlineAssistant::update_global(cx, |this, cx| {
1395                        this.handle_editor_change(editor, cx)
1396                    })
1397                }),
1398                cx.subscribe(editor, move |editor, event, cx| {
1399                    InlineAssistant::update_global(cx, |this, cx| {
1400                        this.handle_editor_event(editor, event, cx)
1401                    })
1402                }),
1403                editor.update(cx, |editor, cx| {
1404                    let editor_handle = cx.view().downgrade();
1405                    editor.register_action(
1406                        move |_: &editor::actions::Newline, cx: &mut WindowContext| {
1407                            InlineAssistant::update_global(cx, |this, cx| {
1408                                if let Some(editor) = editor_handle.upgrade() {
1409                                    this.handle_editor_newline(editor, cx)
1410                                }
1411                            })
1412                        },
1413                    )
1414                }),
1415                editor.update(cx, |editor, cx| {
1416                    let editor_handle = cx.view().downgrade();
1417                    editor.register_action(
1418                        move |_: &editor::actions::Cancel, cx: &mut WindowContext| {
1419                            InlineAssistant::update_global(cx, |this, cx| {
1420                                if let Some(editor) = editor_handle.upgrade() {
1421                                    this.handle_editor_cancel(editor, cx)
1422                                }
1423                            })
1424                        },
1425                    )
1426                }),
1427            ],
1428        }
1429    }
1430}
1431
1432struct InlineAssistGroup {
1433    assist_ids: Vec<InlineAssistId>,
1434    linked: bool,
1435    active_assist_id: Option<InlineAssistId>,
1436}
1437
1438impl InlineAssistGroup {
1439    fn new() -> Self {
1440        Self {
1441            assist_ids: Vec::new(),
1442            linked: true,
1443            active_assist_id: None,
1444        }
1445    }
1446}
1447
1448fn build_assist_editor_renderer(editor: &View<PromptEditor>) -> RenderBlock {
1449    let editor = editor.clone();
1450    Arc::new(move |cx: &mut BlockContext| {
1451        *editor.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
1452        editor.clone().into_any_element()
1453    })
1454}
1455
1456#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1457pub struct InlineAssistId(usize);
1458
1459impl InlineAssistId {
1460    fn post_inc(&mut self) -> InlineAssistId {
1461        let id = *self;
1462        self.0 += 1;
1463        id
1464    }
1465}
1466
1467#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1468struct InlineAssistGroupId(usize);
1469
1470impl InlineAssistGroupId {
1471    fn post_inc(&mut self) -> InlineAssistGroupId {
1472        let id = *self;
1473        self.0 += 1;
1474        id
1475    }
1476}
1477
1478enum PromptEditorEvent {
1479    StartRequested,
1480    StopRequested,
1481    ConfirmRequested,
1482    CancelRequested,
1483    DismissRequested,
1484}
1485
1486struct PromptEditor {
1487    id: InlineAssistId,
1488    editor: View<Editor>,
1489    context_strip: View<ContextStrip>,
1490    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
1491    language_model_selector: View<LanguageModelSelector>,
1492    edited_since_done: bool,
1493    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
1494    prompt_history: VecDeque<String>,
1495    prompt_history_ix: Option<usize>,
1496    pending_prompt: String,
1497    codegen: Model<Codegen>,
1498    _codegen_subscription: Subscription,
1499    editor_subscriptions: Vec<Subscription>,
1500    show_rate_limit_notice: bool,
1501}
1502
1503impl EventEmitter<PromptEditorEvent> for PromptEditor {}
1504
1505impl Render for PromptEditor {
1506    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1507        let gutter_dimensions = *self.gutter_dimensions.lock();
1508        let mut buttons = Vec::new();
1509        let codegen = self.codegen.read(cx);
1510        if codegen.alternative_count(cx) > 1 {
1511            buttons.push(self.render_cycle_controls(cx));
1512        }
1513
1514        let status = codegen.status(cx);
1515        buttons.extend(match status {
1516            CodegenStatus::Idle => {
1517                vec![
1518                    IconButton::new("cancel", IconName::Close)
1519                        .icon_color(Color::Muted)
1520                        .shape(IconButtonShape::Square)
1521                        .tooltip(|cx| Tooltip::for_action("Cancel Assist", &menu::Cancel, cx))
1522                        .on_click(
1523                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1524                        )
1525                        .into_any_element(),
1526                    IconButton::new("start", IconName::SparkleAlt)
1527                        .icon_color(Color::Muted)
1528                        .shape(IconButtonShape::Square)
1529                        .tooltip(|cx| Tooltip::for_action("Transform", &menu::Confirm, cx))
1530                        .on_click(
1531                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::StartRequested)),
1532                        )
1533                        .into_any_element(),
1534                ]
1535            }
1536            CodegenStatus::Pending => {
1537                vec![
1538                    IconButton::new("cancel", IconName::Close)
1539                        .icon_color(Color::Muted)
1540                        .shape(IconButtonShape::Square)
1541                        .tooltip(|cx| Tooltip::text("Cancel Assist", cx))
1542                        .on_click(
1543                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1544                        )
1545                        .into_any_element(),
1546                    IconButton::new("stop", IconName::Stop)
1547                        .icon_color(Color::Error)
1548                        .shape(IconButtonShape::Square)
1549                        .tooltip(|cx| {
1550                            Tooltip::with_meta(
1551                                "Interrupt Transformation",
1552                                Some(&menu::Cancel),
1553                                "Changes won't be discarded",
1554                                cx,
1555                            )
1556                        })
1557                        .on_click(cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::StopRequested)))
1558                        .into_any_element(),
1559                ]
1560            }
1561            CodegenStatus::Error(_) | CodegenStatus::Done => {
1562                vec![
1563                    IconButton::new("cancel", IconName::Close)
1564                        .icon_color(Color::Muted)
1565                        .shape(IconButtonShape::Square)
1566                        .tooltip(|cx| Tooltip::for_action("Cancel Assist", &menu::Cancel, cx))
1567                        .on_click(
1568                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1569                        )
1570                        .into_any_element(),
1571                    if self.edited_since_done || matches!(status, CodegenStatus::Error(_)) {
1572                        IconButton::new("restart", IconName::RotateCw)
1573                            .icon_color(Color::Info)
1574                            .shape(IconButtonShape::Square)
1575                            .tooltip(|cx| {
1576                                Tooltip::with_meta(
1577                                    "Restart Transformation",
1578                                    Some(&menu::Confirm),
1579                                    "Changes will be discarded",
1580                                    cx,
1581                                )
1582                            })
1583                            .on_click(cx.listener(|_, _, cx| {
1584                                cx.emit(PromptEditorEvent::StartRequested);
1585                            }))
1586                            .into_any_element()
1587                    } else {
1588                        IconButton::new("confirm", IconName::Check)
1589                            .icon_color(Color::Info)
1590                            .shape(IconButtonShape::Square)
1591                            .tooltip(|cx| Tooltip::for_action("Confirm Assist", &menu::Confirm, cx))
1592                            .on_click(cx.listener(|_, _, cx| {
1593                                cx.emit(PromptEditorEvent::ConfirmRequested);
1594                            }))
1595                            .into_any_element()
1596                    },
1597                ]
1598            }
1599        });
1600
1601        v_flex()
1602            .border_y_1()
1603            .border_color(cx.theme().status().info_border)
1604            .size_full()
1605            .py(cx.line_height() / 2.5)
1606            .child(
1607                h_flex()
1608                    .key_context("PromptEditor")
1609                    .bg(cx.theme().colors().editor_background)
1610                    .block_mouse_down()
1611                    .cursor(CursorStyle::Arrow)
1612                    .on_action(cx.listener(Self::toggle_context_picker))
1613                    .on_action(cx.listener(Self::confirm))
1614                    .on_action(cx.listener(Self::cancel))
1615                    .on_action(cx.listener(Self::move_up))
1616                    .on_action(cx.listener(Self::move_down))
1617                    .capture_action(cx.listener(Self::cycle_prev))
1618                    .capture_action(cx.listener(Self::cycle_next))
1619                    .child(
1620                        h_flex()
1621                            .w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0))
1622                            .justify_center()
1623                            .gap_2()
1624                            .child(LanguageModelSelectorPopoverMenu::new(
1625                                self.language_model_selector.clone(),
1626                                IconButton::new("context", IconName::SettingsAlt)
1627                                    .shape(IconButtonShape::Square)
1628                                    .icon_size(IconSize::Small)
1629                                    .icon_color(Color::Muted)
1630                                    .tooltip(move |cx| {
1631                                        Tooltip::with_meta(
1632                                            format!(
1633                                                "Using {}",
1634                                                LanguageModelRegistry::read_global(cx)
1635                                                    .active_model()
1636                                                    .map(|model| model.name().0)
1637                                                    .unwrap_or_else(|| "No model selected".into()),
1638                                            ),
1639                                            None,
1640                                            "Change Model",
1641                                            cx,
1642                                        )
1643                                    }),
1644                            ))
1645                            .map(|el| {
1646                                let CodegenStatus::Error(error) = self.codegen.read(cx).status(cx)
1647                                else {
1648                                    return el;
1649                                };
1650
1651                                let error_message = SharedString::from(error.to_string());
1652                                if error.error_code() == proto::ErrorCode::RateLimitExceeded
1653                                    && cx.has_flag::<ZedPro>()
1654                                {
1655                                    el.child(
1656                                        v_flex()
1657                                            .child(
1658                                                IconButton::new(
1659                                                    "rate-limit-error",
1660                                                    IconName::XCircle,
1661                                                )
1662                                                .toggle_state(self.show_rate_limit_notice)
1663                                                .shape(IconButtonShape::Square)
1664                                                .icon_size(IconSize::Small)
1665                                                .on_click(
1666                                                    cx.listener(Self::toggle_rate_limit_notice),
1667                                                ),
1668                                            )
1669                                            .children(self.show_rate_limit_notice.then(|| {
1670                                                deferred(
1671                                                    anchored()
1672                                                        .position_mode(
1673                                                            gpui::AnchoredPositionMode::Local,
1674                                                        )
1675                                                        .position(point(px(0.), px(24.)))
1676                                                        .anchor(gpui::Corner::TopLeft)
1677                                                        .child(self.render_rate_limit_notice(cx)),
1678                                                )
1679                                            })),
1680                                    )
1681                                } else {
1682                                    el.child(
1683                                        div()
1684                                            .id("error")
1685                                            .tooltip(move |cx| {
1686                                                Tooltip::text(error_message.clone(), cx)
1687                                            })
1688                                            .child(
1689                                                Icon::new(IconName::XCircle)
1690                                                    .size(IconSize::Small)
1691                                                    .color(Color::Error),
1692                                            ),
1693                                    )
1694                                }
1695                            }),
1696                    )
1697                    .child(div().flex_1().child(self.render_editor(cx)))
1698                    .child(h_flex().gap_2().pr_6().children(buttons)),
1699            )
1700            .child(
1701                h_flex()
1702                    .child(
1703                        h_flex()
1704                            .w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0))
1705                            .justify_center()
1706                            .gap_2(),
1707                    )
1708                    .child(self.context_strip.clone()),
1709            )
1710    }
1711}
1712
1713impl FocusableView for PromptEditor {
1714    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1715        self.editor.focus_handle(cx)
1716    }
1717}
1718
1719impl PromptEditor {
1720    const MAX_LINES: u8 = 8;
1721
1722    #[allow(clippy::too_many_arguments)]
1723    fn new(
1724        id: InlineAssistId,
1725        gutter_dimensions: Arc<Mutex<GutterDimensions>>,
1726        prompt_history: VecDeque<String>,
1727        prompt_buffer: Model<MultiBuffer>,
1728        codegen: Model<Codegen>,
1729        fs: Arc<dyn Fs>,
1730        context_store: Model<ContextStore>,
1731        workspace: WeakView<Workspace>,
1732        thread_store: Option<WeakModel<ThreadStore>>,
1733        cx: &mut ViewContext<Self>,
1734    ) -> Self {
1735        let prompt_editor = cx.new_view(|cx| {
1736            let mut editor = Editor::new(
1737                EditorMode::AutoHeight {
1738                    max_lines: Self::MAX_LINES as usize,
1739                },
1740                prompt_buffer,
1741                None,
1742                false,
1743                cx,
1744            );
1745            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1746            // Since the prompt editors for all inline assistants are linked,
1747            // always show the cursor (even when it isn't focused) because
1748            // typing in one will make what you typed appear in all of them.
1749            editor.set_show_cursor_when_unfocused(true, cx);
1750            editor.set_placeholder_text(Self::placeholder_text(codegen.read(cx)), cx);
1751            editor
1752        });
1753        let context_picker_menu_handle = PopoverMenuHandle::default();
1754
1755        let mut this = Self {
1756            id,
1757            editor: prompt_editor.clone(),
1758            context_strip: cx.new_view(|cx| {
1759                ContextStrip::new(
1760                    context_store,
1761                    workspace.clone(),
1762                    thread_store.clone(),
1763                    prompt_editor.focus_handle(cx),
1764                    context_picker_menu_handle.clone(),
1765                    cx,
1766                )
1767            }),
1768            context_picker_menu_handle,
1769            language_model_selector: cx.new_view(|cx| {
1770                let fs = fs.clone();
1771                LanguageModelSelector::new(
1772                    move |model, cx| {
1773                        update_settings_file::<AssistantSettings>(
1774                            fs.clone(),
1775                            cx,
1776                            move |settings, _| settings.set_model(model.clone()),
1777                        );
1778                    },
1779                    cx,
1780                )
1781            }),
1782            edited_since_done: false,
1783            gutter_dimensions,
1784            prompt_history,
1785            prompt_history_ix: None,
1786            pending_prompt: String::new(),
1787            _codegen_subscription: cx.observe(&codegen, Self::handle_codegen_changed),
1788            editor_subscriptions: Vec::new(),
1789            codegen,
1790            show_rate_limit_notice: false,
1791        };
1792        this.subscribe_to_editor(cx);
1793        this
1794    }
1795
1796    fn subscribe_to_editor(&mut self, cx: &mut ViewContext<Self>) {
1797        self.editor_subscriptions.clear();
1798        self.editor_subscriptions
1799            .push(cx.subscribe(&self.editor, Self::handle_prompt_editor_events));
1800    }
1801
1802    fn set_show_cursor_when_unfocused(
1803        &mut self,
1804        show_cursor_when_unfocused: bool,
1805        cx: &mut ViewContext<Self>,
1806    ) {
1807        self.editor.update(cx, |editor, cx| {
1808            editor.set_show_cursor_when_unfocused(show_cursor_when_unfocused, cx)
1809        });
1810    }
1811
1812    fn unlink(&mut self, cx: &mut ViewContext<Self>) {
1813        let prompt = self.prompt(cx);
1814        let focus = self.editor.focus_handle(cx).contains_focused(cx);
1815        self.editor = cx.new_view(|cx| {
1816            let mut editor = Editor::auto_height(Self::MAX_LINES as usize, cx);
1817            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1818            editor.set_placeholder_text(Self::placeholder_text(self.codegen.read(cx)), cx);
1819            editor.set_placeholder_text("Add a prompt…", cx);
1820            editor.set_text(prompt, cx);
1821            if focus {
1822                editor.focus(cx);
1823            }
1824            editor
1825        });
1826        self.subscribe_to_editor(cx);
1827    }
1828
1829    fn placeholder_text(codegen: &Codegen) -> String {
1830        let action = if codegen.is_insertion {
1831            "Generate"
1832        } else {
1833            "Transform"
1834        };
1835
1836        format!("{action}… ↓↑ for history")
1837    }
1838
1839    fn prompt(&self, cx: &AppContext) -> String {
1840        self.editor.read(cx).text(cx)
1841    }
1842
1843    fn toggle_rate_limit_notice(&mut self, _: &ClickEvent, cx: &mut ViewContext<Self>) {
1844        self.show_rate_limit_notice = !self.show_rate_limit_notice;
1845        if self.show_rate_limit_notice {
1846            cx.focus_view(&self.editor);
1847        }
1848        cx.notify();
1849    }
1850
1851    fn handle_prompt_editor_events(
1852        &mut self,
1853        _: View<Editor>,
1854        event: &EditorEvent,
1855        cx: &mut ViewContext<Self>,
1856    ) {
1857        match event {
1858            EditorEvent::Edited { .. } => {
1859                if let Some(workspace) = cx.window_handle().downcast::<Workspace>() {
1860                    workspace
1861                        .update(cx, |workspace, cx| {
1862                            let is_via_ssh = workspace
1863                                .project()
1864                                .update(cx, |project, _| project.is_via_ssh());
1865
1866                            workspace
1867                                .client()
1868                                .telemetry()
1869                                .log_edit_event("inline assist", is_via_ssh);
1870                        })
1871                        .log_err();
1872                }
1873                let prompt = self.editor.read(cx).text(cx);
1874                if self
1875                    .prompt_history_ix
1876                    .map_or(true, |ix| self.prompt_history[ix] != prompt)
1877                {
1878                    self.prompt_history_ix.take();
1879                    self.pending_prompt = prompt;
1880                }
1881
1882                self.edited_since_done = true;
1883                cx.notify();
1884            }
1885            EditorEvent::Blurred => {
1886                if self.show_rate_limit_notice {
1887                    self.show_rate_limit_notice = false;
1888                    cx.notify();
1889                }
1890            }
1891            _ => {}
1892        }
1893    }
1894
1895    fn handle_codegen_changed(&mut self, _: Model<Codegen>, cx: &mut ViewContext<Self>) {
1896        match self.codegen.read(cx).status(cx) {
1897            CodegenStatus::Idle => {
1898                self.editor
1899                    .update(cx, |editor, _| editor.set_read_only(false));
1900            }
1901            CodegenStatus::Pending => {
1902                self.editor
1903                    .update(cx, |editor, _| editor.set_read_only(true));
1904            }
1905            CodegenStatus::Done => {
1906                self.edited_since_done = false;
1907                self.editor
1908                    .update(cx, |editor, _| editor.set_read_only(false));
1909            }
1910            CodegenStatus::Error(error) => {
1911                if cx.has_flag::<ZedPro>()
1912                    && error.error_code() == proto::ErrorCode::RateLimitExceeded
1913                    && !dismissed_rate_limit_notice()
1914                {
1915                    self.show_rate_limit_notice = true;
1916                    cx.notify();
1917                }
1918
1919                self.edited_since_done = false;
1920                self.editor
1921                    .update(cx, |editor, _| editor.set_read_only(false));
1922            }
1923        }
1924    }
1925
1926    fn toggle_context_picker(&mut self, _: &ToggleContextPicker, cx: &mut ViewContext<Self>) {
1927        self.context_picker_menu_handle.toggle(cx);
1928    }
1929
1930    fn cancel(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1931        match self.codegen.read(cx).status(cx) {
1932            CodegenStatus::Idle | CodegenStatus::Done | CodegenStatus::Error(_) => {
1933                cx.emit(PromptEditorEvent::CancelRequested);
1934            }
1935            CodegenStatus::Pending => {
1936                cx.emit(PromptEditorEvent::StopRequested);
1937            }
1938        }
1939    }
1940
1941    fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
1942        match self.codegen.read(cx).status(cx) {
1943            CodegenStatus::Idle => {
1944                cx.emit(PromptEditorEvent::StartRequested);
1945            }
1946            CodegenStatus::Pending => {
1947                cx.emit(PromptEditorEvent::DismissRequested);
1948            }
1949            CodegenStatus::Done => {
1950                if self.edited_since_done {
1951                    cx.emit(PromptEditorEvent::StartRequested);
1952                } else {
1953                    cx.emit(PromptEditorEvent::ConfirmRequested);
1954                }
1955            }
1956            CodegenStatus::Error(_) => {
1957                cx.emit(PromptEditorEvent::StartRequested);
1958            }
1959        }
1960    }
1961
1962    fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
1963        if let Some(ix) = self.prompt_history_ix {
1964            if ix > 0 {
1965                self.prompt_history_ix = Some(ix - 1);
1966                let prompt = self.prompt_history[ix - 1].as_str();
1967                self.editor.update(cx, |editor, cx| {
1968                    editor.set_text(prompt, cx);
1969                    editor.move_to_beginning(&Default::default(), cx);
1970                });
1971            }
1972        } else if !self.prompt_history.is_empty() {
1973            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
1974            let prompt = self.prompt_history[self.prompt_history.len() - 1].as_str();
1975            self.editor.update(cx, |editor, cx| {
1976                editor.set_text(prompt, cx);
1977                editor.move_to_beginning(&Default::default(), cx);
1978            });
1979        }
1980    }
1981
1982    fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
1983        if let Some(ix) = self.prompt_history_ix {
1984            if ix < self.prompt_history.len() - 1 {
1985                self.prompt_history_ix = Some(ix + 1);
1986                let prompt = self.prompt_history[ix + 1].as_str();
1987                self.editor.update(cx, |editor, cx| {
1988                    editor.set_text(prompt, cx);
1989                    editor.move_to_end(&Default::default(), cx)
1990                });
1991            } else {
1992                self.prompt_history_ix = None;
1993                let prompt = self.pending_prompt.as_str();
1994                self.editor.update(cx, |editor, cx| {
1995                    editor.set_text(prompt, cx);
1996                    editor.move_to_end(&Default::default(), cx)
1997                });
1998            }
1999        }
2000    }
2001
2002    fn cycle_prev(&mut self, _: &CyclePreviousInlineAssist, cx: &mut ViewContext<Self>) {
2003        self.codegen
2004            .update(cx, |codegen, cx| codegen.cycle_prev(cx));
2005    }
2006
2007    fn cycle_next(&mut self, _: &CycleNextInlineAssist, cx: &mut ViewContext<Self>) {
2008        self.codegen
2009            .update(cx, |codegen, cx| codegen.cycle_next(cx));
2010    }
2011
2012    fn render_cycle_controls(&self, cx: &ViewContext<Self>) -> AnyElement {
2013        let codegen = self.codegen.read(cx);
2014        let disabled = matches!(codegen.status(cx), CodegenStatus::Idle);
2015
2016        let model_registry = LanguageModelRegistry::read_global(cx);
2017        let default_model = model_registry.active_model();
2018        let alternative_models = model_registry.inline_alternative_models();
2019
2020        let get_model_name = |index: usize| -> String {
2021            let name = |model: &Arc<dyn LanguageModel>| model.name().0.to_string();
2022
2023            match index {
2024                0 => default_model.as_ref().map_or_else(String::new, name),
2025                index if index <= alternative_models.len() => alternative_models
2026                    .get(index - 1)
2027                    .map_or_else(String::new, name),
2028                _ => String::new(),
2029            }
2030        };
2031
2032        let total_models = alternative_models.len() + 1;
2033
2034        if total_models <= 1 {
2035            return div().into_any_element();
2036        }
2037
2038        let current_index = codegen.active_alternative;
2039        let prev_index = (current_index + total_models - 1) % total_models;
2040        let next_index = (current_index + 1) % total_models;
2041
2042        let prev_model_name = get_model_name(prev_index);
2043        let next_model_name = get_model_name(next_index);
2044
2045        h_flex()
2046            .child(
2047                IconButton::new("previous", IconName::ChevronLeft)
2048                    .icon_color(Color::Muted)
2049                    .disabled(disabled || current_index == 0)
2050                    .shape(IconButtonShape::Square)
2051                    .tooltip({
2052                        let focus_handle = self.editor.focus_handle(cx);
2053                        move |cx| {
2054                            cx.new_view(|cx| {
2055                                let mut tooltip = Tooltip::new("Previous Alternative").key_binding(
2056                                    KeyBinding::for_action_in(
2057                                        &CyclePreviousInlineAssist,
2058                                        &focus_handle,
2059                                        cx,
2060                                    ),
2061                                );
2062                                if !disabled && current_index != 0 {
2063                                    tooltip = tooltip.meta(prev_model_name.clone());
2064                                }
2065                                tooltip
2066                            })
2067                            .into()
2068                        }
2069                    })
2070                    .on_click(cx.listener(|this, _, cx| {
2071                        this.codegen
2072                            .update(cx, |codegen, cx| codegen.cycle_prev(cx))
2073                    })),
2074            )
2075            .child(
2076                Label::new(format!(
2077                    "{}/{}",
2078                    codegen.active_alternative + 1,
2079                    codegen.alternative_count(cx)
2080                ))
2081                .size(LabelSize::Small)
2082                .color(if disabled {
2083                    Color::Disabled
2084                } else {
2085                    Color::Muted
2086                }),
2087            )
2088            .child(
2089                IconButton::new("next", IconName::ChevronRight)
2090                    .icon_color(Color::Muted)
2091                    .disabled(disabled || current_index == total_models - 1)
2092                    .shape(IconButtonShape::Square)
2093                    .tooltip({
2094                        let focus_handle = self.editor.focus_handle(cx);
2095                        move |cx| {
2096                            cx.new_view(|cx| {
2097                                let mut tooltip = Tooltip::new("Next Alternative").key_binding(
2098                                    KeyBinding::for_action_in(
2099                                        &CycleNextInlineAssist,
2100                                        &focus_handle,
2101                                        cx,
2102                                    ),
2103                                );
2104                                if !disabled && current_index != total_models - 1 {
2105                                    tooltip = tooltip.meta(next_model_name.clone());
2106                                }
2107                                tooltip
2108                            })
2109                            .into()
2110                        }
2111                    })
2112                    .on_click(cx.listener(|this, _, cx| {
2113                        this.codegen
2114                            .update(cx, |codegen, cx| codegen.cycle_next(cx))
2115                    })),
2116            )
2117            .into_any_element()
2118    }
2119
2120    fn render_rate_limit_notice(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2121        Popover::new().child(
2122            v_flex()
2123                .occlude()
2124                .p_2()
2125                .child(
2126                    Label::new("Out of Tokens")
2127                        .size(LabelSize::Small)
2128                        .weight(FontWeight::BOLD),
2129                )
2130                .child(Label::new(
2131                    "Try Zed Pro for higher limits, a wider range of models, and more.",
2132                ))
2133                .child(
2134                    h_flex()
2135                        .justify_between()
2136                        .child(CheckboxWithLabel::new(
2137                            "dont-show-again",
2138                            Label::new("Don't show again"),
2139                            if dismissed_rate_limit_notice() {
2140                                ui::ToggleState::Selected
2141                            } else {
2142                                ui::ToggleState::Unselected
2143                            },
2144                            |selection, cx| {
2145                                let is_dismissed = match selection {
2146                                    ui::ToggleState::Unselected => false,
2147                                    ui::ToggleState::Indeterminate => return,
2148                                    ui::ToggleState::Selected => true,
2149                                };
2150
2151                                set_rate_limit_notice_dismissed(is_dismissed, cx)
2152                            },
2153                        ))
2154                        .child(
2155                            h_flex()
2156                                .gap_2()
2157                                .child(
2158                                    Button::new("dismiss", "Dismiss")
2159                                        .style(ButtonStyle::Transparent)
2160                                        .on_click(cx.listener(Self::toggle_rate_limit_notice)),
2161                                )
2162                                .child(Button::new("more-info", "More Info").on_click(
2163                                    |_event, cx| {
2164                                        cx.dispatch_action(Box::new(
2165                                            zed_actions::OpenAccountSettings,
2166                                        ))
2167                                    },
2168                                )),
2169                        ),
2170                ),
2171        )
2172    }
2173
2174    fn render_editor(&mut self, cx: &mut ViewContext<Self>) -> AnyElement {
2175        let font_size = TextSize::Default.rems(cx);
2176        let line_height = font_size.to_pixels(cx.rem_size()) * 1.3;
2177
2178        v_flex()
2179            .key_context("MessageEditor")
2180            .size_full()
2181            .gap_2()
2182            .p_2()
2183            .bg(cx.theme().colors().editor_background)
2184            .child({
2185                let settings = ThemeSettings::get_global(cx);
2186                let text_style = TextStyle {
2187                    color: cx.theme().colors().editor_foreground,
2188                    font_family: settings.ui_font.family.clone(),
2189                    font_features: settings.ui_font.features.clone(),
2190                    font_size: font_size.into(),
2191                    font_weight: settings.ui_font.weight,
2192                    line_height: line_height.into(),
2193                    ..Default::default()
2194                };
2195
2196                EditorElement::new(
2197                    &self.editor,
2198                    EditorStyle {
2199                        background: cx.theme().colors().editor_background,
2200                        local_player: cx.theme().players().local(),
2201                        text: text_style,
2202                        ..Default::default()
2203                    },
2204                )
2205            })
2206            .into_any_element()
2207    }
2208}
2209
2210const DISMISSED_RATE_LIMIT_NOTICE_KEY: &str = "dismissed-rate-limit-notice";
2211
2212fn dismissed_rate_limit_notice() -> bool {
2213    db::kvp::KEY_VALUE_STORE
2214        .read_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY)
2215        .log_err()
2216        .map_or(false, |s| s.is_some())
2217}
2218
2219fn set_rate_limit_notice_dismissed(is_dismissed: bool, cx: &mut AppContext) {
2220    db::write_and_log(cx, move || async move {
2221        if is_dismissed {
2222            db::kvp::KEY_VALUE_STORE
2223                .write_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into(), "1".into())
2224                .await
2225        } else {
2226            db::kvp::KEY_VALUE_STORE
2227                .delete_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into())
2228                .await
2229        }
2230    })
2231}
2232
2233pub struct InlineAssist {
2234    group_id: InlineAssistGroupId,
2235    range: Range<Anchor>,
2236    editor: WeakView<Editor>,
2237    decorations: Option<InlineAssistDecorations>,
2238    codegen: Model<Codegen>,
2239    _subscriptions: Vec<Subscription>,
2240    workspace: WeakView<Workspace>,
2241}
2242
2243impl InlineAssist {
2244    #[allow(clippy::too_many_arguments)]
2245    fn new(
2246        assist_id: InlineAssistId,
2247        group_id: InlineAssistGroupId,
2248        editor: &View<Editor>,
2249        prompt_editor: &View<PromptEditor>,
2250        prompt_block_id: CustomBlockId,
2251        end_block_id: CustomBlockId,
2252        range: Range<Anchor>,
2253        codegen: Model<Codegen>,
2254        workspace: WeakView<Workspace>,
2255        cx: &mut WindowContext,
2256    ) -> Self {
2257        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
2258        InlineAssist {
2259            group_id,
2260            editor: editor.downgrade(),
2261            decorations: Some(InlineAssistDecorations {
2262                prompt_block_id,
2263                prompt_editor: prompt_editor.clone(),
2264                removed_line_block_ids: HashSet::default(),
2265                end_block_id,
2266            }),
2267            range,
2268            codegen: codegen.clone(),
2269            workspace: workspace.clone(),
2270            _subscriptions: vec![
2271                cx.on_focus_in(&prompt_editor_focus_handle, move |cx| {
2272                    InlineAssistant::update_global(cx, |this, cx| {
2273                        this.handle_prompt_editor_focus_in(assist_id, cx)
2274                    })
2275                }),
2276                cx.on_focus_out(&prompt_editor_focus_handle, move |_, cx| {
2277                    InlineAssistant::update_global(cx, |this, cx| {
2278                        this.handle_prompt_editor_focus_out(assist_id, cx)
2279                    })
2280                }),
2281                cx.subscribe(prompt_editor, |prompt_editor, event, cx| {
2282                    InlineAssistant::update_global(cx, |this, cx| {
2283                        this.handle_prompt_editor_event(prompt_editor, event, cx)
2284                    })
2285                }),
2286                cx.observe(&codegen, {
2287                    let editor = editor.downgrade();
2288                    move |_, cx| {
2289                        if let Some(editor) = editor.upgrade() {
2290                            InlineAssistant::update_global(cx, |this, cx| {
2291                                if let Some(editor_assists) =
2292                                    this.assists_by_editor.get(&editor.downgrade())
2293                                {
2294                                    editor_assists.highlight_updates.send(()).ok();
2295                                }
2296
2297                                this.update_editor_blocks(&editor, assist_id, cx);
2298                            })
2299                        }
2300                    }
2301                }),
2302                cx.subscribe(&codegen, move |codegen, event, cx| {
2303                    InlineAssistant::update_global(cx, |this, cx| match event {
2304                        CodegenEvent::Undone => this.finish_assist(assist_id, false, cx),
2305                        CodegenEvent::Finished => {
2306                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
2307                                assist
2308                            } else {
2309                                return;
2310                            };
2311
2312                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx) {
2313                                if assist.decorations.is_none() {
2314                                    if let Some(workspace) = assist.workspace.upgrade() {
2315                                        let error = format!("Inline assistant error: {}", error);
2316                                        workspace.update(cx, |workspace, cx| {
2317                                            struct InlineAssistantError;
2318
2319                                            let id =
2320                                                NotificationId::composite::<InlineAssistantError>(
2321                                                    assist_id.0,
2322                                                );
2323
2324                                            workspace.show_toast(Toast::new(id, error), cx);
2325                                        })
2326                                    }
2327                                }
2328                            }
2329
2330                            if assist.decorations.is_none() {
2331                                this.finish_assist(assist_id, false, cx);
2332                            }
2333                        }
2334                    })
2335                }),
2336            ],
2337        }
2338    }
2339
2340    fn user_prompt(&self, cx: &AppContext) -> Option<String> {
2341        let decorations = self.decorations.as_ref()?;
2342        Some(decorations.prompt_editor.read(cx).prompt(cx))
2343    }
2344}
2345
2346struct InlineAssistDecorations {
2347    prompt_block_id: CustomBlockId,
2348    prompt_editor: View<PromptEditor>,
2349    removed_line_block_ids: HashSet<CustomBlockId>,
2350    end_block_id: CustomBlockId,
2351}
2352
2353#[derive(Copy, Clone, Debug)]
2354pub enum CodegenEvent {
2355    Finished,
2356    Undone,
2357}
2358
2359pub struct Codegen {
2360    alternatives: Vec<Model<CodegenAlternative>>,
2361    active_alternative: usize,
2362    seen_alternatives: HashSet<usize>,
2363    subscriptions: Vec<Subscription>,
2364    buffer: Model<MultiBuffer>,
2365    range: Range<Anchor>,
2366    initial_transaction_id: Option<TransactionId>,
2367    context_store: Model<ContextStore>,
2368    telemetry: Arc<Telemetry>,
2369    builder: Arc<PromptBuilder>,
2370    is_insertion: bool,
2371}
2372
2373impl Codegen {
2374    pub fn new(
2375        buffer: Model<MultiBuffer>,
2376        range: Range<Anchor>,
2377        initial_transaction_id: Option<TransactionId>,
2378        context_store: Model<ContextStore>,
2379        telemetry: Arc<Telemetry>,
2380        builder: Arc<PromptBuilder>,
2381        cx: &mut ModelContext<Self>,
2382    ) -> Self {
2383        let codegen = cx.new_model(|cx| {
2384            CodegenAlternative::new(
2385                buffer.clone(),
2386                range.clone(),
2387                false,
2388                Some(context_store.clone()),
2389                Some(telemetry.clone()),
2390                builder.clone(),
2391                cx,
2392            )
2393        });
2394        let mut this = Self {
2395            is_insertion: range.to_offset(&buffer.read(cx).snapshot(cx)).is_empty(),
2396            alternatives: vec![codegen],
2397            active_alternative: 0,
2398            seen_alternatives: HashSet::default(),
2399            subscriptions: Vec::new(),
2400            buffer,
2401            range,
2402            initial_transaction_id,
2403            context_store,
2404            telemetry,
2405            builder,
2406        };
2407        this.activate(0, cx);
2408        this
2409    }
2410
2411    fn subscribe_to_alternative(&mut self, cx: &mut ModelContext<Self>) {
2412        let codegen = self.active_alternative().clone();
2413        self.subscriptions.clear();
2414        self.subscriptions
2415            .push(cx.observe(&codegen, |_, _, cx| cx.notify()));
2416        self.subscriptions
2417            .push(cx.subscribe(&codegen, |_, _, event, cx| cx.emit(*event)));
2418    }
2419
2420    fn active_alternative(&self) -> &Model<CodegenAlternative> {
2421        &self.alternatives[self.active_alternative]
2422    }
2423
2424    fn status<'a>(&self, cx: &'a AppContext) -> &'a CodegenStatus {
2425        &self.active_alternative().read(cx).status
2426    }
2427
2428    fn alternative_count(&self, cx: &AppContext) -> usize {
2429        LanguageModelRegistry::read_global(cx)
2430            .inline_alternative_models()
2431            .len()
2432            + 1
2433    }
2434
2435    pub fn cycle_prev(&mut self, cx: &mut ModelContext<Self>) {
2436        let next_active_ix = if self.active_alternative == 0 {
2437            self.alternatives.len() - 1
2438        } else {
2439            self.active_alternative - 1
2440        };
2441        self.activate(next_active_ix, cx);
2442    }
2443
2444    pub fn cycle_next(&mut self, cx: &mut ModelContext<Self>) {
2445        let next_active_ix = (self.active_alternative + 1) % self.alternatives.len();
2446        self.activate(next_active_ix, cx);
2447    }
2448
2449    fn activate(&mut self, index: usize, cx: &mut ModelContext<Self>) {
2450        self.active_alternative()
2451            .update(cx, |codegen, cx| codegen.set_active(false, cx));
2452        self.seen_alternatives.insert(index);
2453        self.active_alternative = index;
2454        self.active_alternative()
2455            .update(cx, |codegen, cx| codegen.set_active(true, cx));
2456        self.subscribe_to_alternative(cx);
2457        cx.notify();
2458    }
2459
2460    pub fn start(&mut self, user_prompt: String, cx: &mut ModelContext<Self>) -> Result<()> {
2461        let alternative_models = LanguageModelRegistry::read_global(cx)
2462            .inline_alternative_models()
2463            .to_vec();
2464
2465        self.active_alternative()
2466            .update(cx, |alternative, cx| alternative.undo(cx));
2467        self.activate(0, cx);
2468        self.alternatives.truncate(1);
2469
2470        for _ in 0..alternative_models.len() {
2471            self.alternatives.push(cx.new_model(|cx| {
2472                CodegenAlternative::new(
2473                    self.buffer.clone(),
2474                    self.range.clone(),
2475                    false,
2476                    Some(self.context_store.clone()),
2477                    Some(self.telemetry.clone()),
2478                    self.builder.clone(),
2479                    cx,
2480                )
2481            }));
2482        }
2483
2484        let primary_model = LanguageModelRegistry::read_global(cx)
2485            .active_model()
2486            .context("no active model")?;
2487
2488        for (model, alternative) in iter::once(primary_model)
2489            .chain(alternative_models)
2490            .zip(&self.alternatives)
2491        {
2492            alternative.update(cx, |alternative, cx| {
2493                alternative.start(user_prompt.clone(), model.clone(), cx)
2494            })?;
2495        }
2496
2497        Ok(())
2498    }
2499
2500    pub fn stop(&mut self, cx: &mut ModelContext<Self>) {
2501        for codegen in &self.alternatives {
2502            codegen.update(cx, |codegen, cx| codegen.stop(cx));
2503        }
2504    }
2505
2506    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
2507        self.active_alternative()
2508            .update(cx, |codegen, cx| codegen.undo(cx));
2509
2510        self.buffer.update(cx, |buffer, cx| {
2511            if let Some(transaction_id) = self.initial_transaction_id.take() {
2512                buffer.undo_transaction(transaction_id, cx);
2513                buffer.refresh_preview(cx);
2514            }
2515        });
2516    }
2517
2518    pub fn buffer(&self, cx: &AppContext) -> Model<MultiBuffer> {
2519        self.active_alternative().read(cx).buffer.clone()
2520    }
2521
2522    pub fn old_buffer(&self, cx: &AppContext) -> Model<Buffer> {
2523        self.active_alternative().read(cx).old_buffer.clone()
2524    }
2525
2526    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
2527        self.active_alternative().read(cx).snapshot.clone()
2528    }
2529
2530    pub fn edit_position(&self, cx: &AppContext) -> Option<Anchor> {
2531        self.active_alternative().read(cx).edit_position
2532    }
2533
2534    fn diff<'a>(&self, cx: &'a AppContext) -> &'a Diff {
2535        &self.active_alternative().read(cx).diff
2536    }
2537
2538    pub fn last_equal_ranges<'a>(&self, cx: &'a AppContext) -> &'a [Range<Anchor>] {
2539        self.active_alternative().read(cx).last_equal_ranges()
2540    }
2541}
2542
2543impl EventEmitter<CodegenEvent> for Codegen {}
2544
2545pub struct CodegenAlternative {
2546    buffer: Model<MultiBuffer>,
2547    old_buffer: Model<Buffer>,
2548    snapshot: MultiBufferSnapshot,
2549    edit_position: Option<Anchor>,
2550    range: Range<Anchor>,
2551    last_equal_ranges: Vec<Range<Anchor>>,
2552    transformation_transaction_id: Option<TransactionId>,
2553    status: CodegenStatus,
2554    generation: Task<()>,
2555    diff: Diff,
2556    context_store: Option<Model<ContextStore>>,
2557    telemetry: Option<Arc<Telemetry>>,
2558    _subscription: gpui::Subscription,
2559    builder: Arc<PromptBuilder>,
2560    active: bool,
2561    edits: Vec<(Range<Anchor>, String)>,
2562    line_operations: Vec<LineOperation>,
2563    request: Option<LanguageModelRequest>,
2564    elapsed_time: Option<f64>,
2565    completion: Option<String>,
2566    message_id: Option<String>,
2567}
2568
2569enum CodegenStatus {
2570    Idle,
2571    Pending,
2572    Done,
2573    Error(anyhow::Error),
2574}
2575
2576#[derive(Default)]
2577struct Diff {
2578    deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
2579    inserted_row_ranges: Vec<Range<Anchor>>,
2580}
2581
2582impl Diff {
2583    fn is_empty(&self) -> bool {
2584        self.deleted_row_ranges.is_empty() && self.inserted_row_ranges.is_empty()
2585    }
2586}
2587
2588impl EventEmitter<CodegenEvent> for CodegenAlternative {}
2589
2590impl CodegenAlternative {
2591    pub fn new(
2592        buffer: Model<MultiBuffer>,
2593        range: Range<Anchor>,
2594        active: bool,
2595        context_store: Option<Model<ContextStore>>,
2596        telemetry: Option<Arc<Telemetry>>,
2597        builder: Arc<PromptBuilder>,
2598        cx: &mut ModelContext<Self>,
2599    ) -> Self {
2600        let snapshot = buffer.read(cx).snapshot(cx);
2601
2602        let (old_buffer, _, _) = buffer
2603            .read(cx)
2604            .range_to_buffer_ranges(range.clone(), cx)
2605            .pop()
2606            .unwrap();
2607        let old_buffer = cx.new_model(|cx| {
2608            let old_buffer = old_buffer.read(cx);
2609            let text = old_buffer.as_rope().clone();
2610            let line_ending = old_buffer.line_ending();
2611            let language = old_buffer.language().cloned();
2612            let language_registry = old_buffer.language_registry();
2613
2614            let mut buffer = Buffer::local_normalized(text, line_ending, cx);
2615            buffer.set_language(language, cx);
2616            if let Some(language_registry) = language_registry {
2617                buffer.set_language_registry(language_registry)
2618            }
2619            buffer
2620        });
2621
2622        Self {
2623            buffer: buffer.clone(),
2624            old_buffer,
2625            edit_position: None,
2626            message_id: None,
2627            snapshot,
2628            last_equal_ranges: Default::default(),
2629            transformation_transaction_id: None,
2630            status: CodegenStatus::Idle,
2631            generation: Task::ready(()),
2632            diff: Diff::default(),
2633            context_store,
2634            telemetry,
2635            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
2636            builder,
2637            active,
2638            edits: Vec::new(),
2639            line_operations: Vec::new(),
2640            range,
2641            request: None,
2642            elapsed_time: None,
2643            completion: None,
2644        }
2645    }
2646
2647    fn set_active(&mut self, active: bool, cx: &mut ModelContext<Self>) {
2648        if active != self.active {
2649            self.active = active;
2650
2651            if self.active {
2652                let edits = self.edits.clone();
2653                self.apply_edits(edits, cx);
2654                if matches!(self.status, CodegenStatus::Pending) {
2655                    let line_operations = self.line_operations.clone();
2656                    self.reapply_line_based_diff(line_operations, cx);
2657                } else {
2658                    self.reapply_batch_diff(cx).detach();
2659                }
2660            } else if let Some(transaction_id) = self.transformation_transaction_id.take() {
2661                self.buffer.update(cx, |buffer, cx| {
2662                    buffer.undo_transaction(transaction_id, cx);
2663                    buffer.forget_transaction(transaction_id, cx);
2664                });
2665            }
2666        }
2667    }
2668
2669    fn handle_buffer_event(
2670        &mut self,
2671        _buffer: Model<MultiBuffer>,
2672        event: &multi_buffer::Event,
2673        cx: &mut ModelContext<Self>,
2674    ) {
2675        if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
2676            if self.transformation_transaction_id == Some(*transaction_id) {
2677                self.transformation_transaction_id = None;
2678                self.generation = Task::ready(());
2679                cx.emit(CodegenEvent::Undone);
2680            }
2681        }
2682    }
2683
2684    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
2685        &self.last_equal_ranges
2686    }
2687
2688    pub fn start(
2689        &mut self,
2690        user_prompt: String,
2691        model: Arc<dyn LanguageModel>,
2692        cx: &mut ModelContext<Self>,
2693    ) -> Result<()> {
2694        if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
2695            self.buffer.update(cx, |buffer, cx| {
2696                buffer.undo_transaction(transformation_transaction_id, cx);
2697            });
2698        }
2699
2700        self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
2701
2702        let api_key = model.api_key(cx);
2703        let telemetry_id = model.telemetry_id();
2704        let provider_id = model.provider_id();
2705        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
2706            if user_prompt.trim().to_lowercase() == "delete" {
2707                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
2708            } else {
2709                let request = self.build_request(user_prompt, cx)?;
2710                self.request = Some(request.clone());
2711
2712                cx.spawn(|_, cx| async move { model.stream_completion_text(request, &cx).await })
2713                    .boxed_local()
2714            };
2715        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
2716        Ok(())
2717    }
2718
2719    fn build_request(
2720        &self,
2721        user_prompt: String,
2722        cx: &mut AppContext,
2723    ) -> Result<LanguageModelRequest> {
2724        let buffer = self.buffer.read(cx).snapshot(cx);
2725        let language = buffer.language_at(self.range.start);
2726        let language_name = if let Some(language) = language.as_ref() {
2727            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
2728                None
2729            } else {
2730                Some(language.name())
2731            }
2732        } else {
2733            None
2734        };
2735
2736        let language_name = language_name.as_ref();
2737        let start = buffer.point_to_buffer_offset(self.range.start);
2738        let end = buffer.point_to_buffer_offset(self.range.end);
2739        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
2740            let (start_buffer, start_buffer_offset) = start;
2741            let (end_buffer, end_buffer_offset) = end;
2742            if start_buffer.remote_id() == end_buffer.remote_id() {
2743                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
2744            } else {
2745                return Err(anyhow::anyhow!("invalid transformation range"));
2746            }
2747        } else {
2748            return Err(anyhow::anyhow!("invalid transformation range"));
2749        };
2750
2751        let prompt = self
2752            .builder
2753            .generate_inline_transformation_prompt(user_prompt, language_name, buffer, range)
2754            .map_err(|e| anyhow::anyhow!("Failed to generate content prompt: {}", e))?;
2755
2756        let mut request_message = LanguageModelRequestMessage {
2757            role: Role::User,
2758            content: Vec::new(),
2759            cache: false,
2760        };
2761
2762        if let Some(context_store) = &self.context_store {
2763            let context = context_store.update(cx, |this, _cx| this.context().clone());
2764            attach_context_to_message(&mut request_message, context);
2765        }
2766
2767        request_message.content.push(prompt.into());
2768
2769        Ok(LanguageModelRequest {
2770            tools: Vec::new(),
2771            stop: Vec::new(),
2772            temperature: None,
2773            messages: vec![request_message],
2774        })
2775    }
2776
2777    pub fn handle_stream(
2778        &mut self,
2779        model_telemetry_id: String,
2780        model_provider_id: String,
2781        model_api_key: Option<String>,
2782        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
2783        cx: &mut ModelContext<Self>,
2784    ) {
2785        let start_time = Instant::now();
2786        let snapshot = self.snapshot.clone();
2787        let selected_text = snapshot
2788            .text_for_range(self.range.start..self.range.end)
2789            .collect::<Rope>();
2790
2791        let selection_start = self.range.start.to_point(&snapshot);
2792
2793        // Start with the indentation of the first line in the selection
2794        let mut suggested_line_indent = snapshot
2795            .suggested_indents(selection_start.row..=selection_start.row, cx)
2796            .into_values()
2797            .next()
2798            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
2799
2800        // If the first line in the selection does not have indentation, check the following lines
2801        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
2802            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
2803                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
2804                // Prefer tabs if a line in the selection uses tabs as indentation
2805                if line_indent.kind == IndentKind::Tab {
2806                    suggested_line_indent.kind = IndentKind::Tab;
2807                    break;
2808                }
2809            }
2810        }
2811
2812        let http_client = cx.http_client().clone();
2813        let telemetry = self.telemetry.clone();
2814        let language_name = {
2815            let multibuffer = self.buffer.read(cx);
2816            let ranges = multibuffer.range_to_buffer_ranges(self.range.clone(), cx);
2817            ranges
2818                .first()
2819                .and_then(|(buffer, _, _)| buffer.read(cx).language())
2820                .map(|language| language.name())
2821        };
2822
2823        self.diff = Diff::default();
2824        self.status = CodegenStatus::Pending;
2825        let mut edit_start = self.range.start.to_offset(&snapshot);
2826        let completion = Arc::new(Mutex::new(String::new()));
2827        let completion_clone = completion.clone();
2828
2829        self.generation = cx.spawn(|codegen, mut cx| {
2830            async move {
2831                let stream = stream.await;
2832                let message_id = stream
2833                    .as_ref()
2834                    .ok()
2835                    .and_then(|stream| stream.message_id.clone());
2836                let generate = async {
2837                    let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
2838                    let executor = cx.background_executor().clone();
2839                    let message_id = message_id.clone();
2840                    let line_based_stream_diff: Task<anyhow::Result<()>> =
2841                        cx.background_executor().spawn(async move {
2842                            let mut response_latency = None;
2843                            let request_start = Instant::now();
2844                            let diff = async {
2845                                let chunks = StripInvalidSpans::new(stream?.stream);
2846                                futures::pin_mut!(chunks);
2847                                let mut diff = StreamingDiff::new(selected_text.to_string());
2848                                let mut line_diff = LineDiff::default();
2849
2850                                let mut new_text = String::new();
2851                                let mut base_indent = None;
2852                                let mut line_indent = None;
2853                                let mut first_line = true;
2854
2855                                while let Some(chunk) = chunks.next().await {
2856                                    if response_latency.is_none() {
2857                                        response_latency = Some(request_start.elapsed());
2858                                    }
2859                                    let chunk = chunk?;
2860                                    completion_clone.lock().push_str(&chunk);
2861
2862                                    let mut lines = chunk.split('\n').peekable();
2863                                    while let Some(line) = lines.next() {
2864                                        new_text.push_str(line);
2865                                        if line_indent.is_none() {
2866                                            if let Some(non_whitespace_ch_ix) =
2867                                                new_text.find(|ch: char| !ch.is_whitespace())
2868                                            {
2869                                                line_indent = Some(non_whitespace_ch_ix);
2870                                                base_indent = base_indent.or(line_indent);
2871
2872                                                let line_indent = line_indent.unwrap();
2873                                                let base_indent = base_indent.unwrap();
2874                                                let indent_delta =
2875                                                    line_indent as i32 - base_indent as i32;
2876                                                let mut corrected_indent_len = cmp::max(
2877                                                    0,
2878                                                    suggested_line_indent.len as i32 + indent_delta,
2879                                                )
2880                                                    as usize;
2881                                                if first_line {
2882                                                    corrected_indent_len = corrected_indent_len
2883                                                        .saturating_sub(
2884                                                            selection_start.column as usize,
2885                                                        );
2886                                                }
2887
2888                                                let indent_char = suggested_line_indent.char();
2889                                                let mut indent_buffer = [0; 4];
2890                                                let indent_str =
2891                                                    indent_char.encode_utf8(&mut indent_buffer);
2892                                                new_text.replace_range(
2893                                                    ..line_indent,
2894                                                    &indent_str.repeat(corrected_indent_len),
2895                                                );
2896                                            }
2897                                        }
2898
2899                                        if line_indent.is_some() {
2900                                            let char_ops = diff.push_new(&new_text);
2901                                            line_diff
2902                                                .push_char_operations(&char_ops, &selected_text);
2903                                            diff_tx
2904                                                .send((char_ops, line_diff.line_operations()))
2905                                                .await?;
2906                                            new_text.clear();
2907                                        }
2908
2909                                        if lines.peek().is_some() {
2910                                            let char_ops = diff.push_new("\n");
2911                                            line_diff
2912                                                .push_char_operations(&char_ops, &selected_text);
2913                                            diff_tx
2914                                                .send((char_ops, line_diff.line_operations()))
2915                                                .await?;
2916                                            if line_indent.is_none() {
2917                                                // Don't write out the leading indentation in empty lines on the next line
2918                                                // This is the case where the above if statement didn't clear the buffer
2919                                                new_text.clear();
2920                                            }
2921                                            line_indent = None;
2922                                            first_line = false;
2923                                        }
2924                                    }
2925                                }
2926
2927                                let mut char_ops = diff.push_new(&new_text);
2928                                char_ops.extend(diff.finish());
2929                                line_diff.push_char_operations(&char_ops, &selected_text);
2930                                line_diff.finish(&selected_text);
2931                                diff_tx
2932                                    .send((char_ops, line_diff.line_operations()))
2933                                    .await?;
2934
2935                                anyhow::Ok(())
2936                            };
2937
2938                            let result = diff.await;
2939
2940                            let error_message =
2941                                result.as_ref().err().map(|error| error.to_string());
2942                            report_assistant_event(
2943                                AssistantEvent {
2944                                    conversation_id: None,
2945                                    message_id,
2946                                    kind: AssistantKind::Inline,
2947                                    phase: AssistantPhase::Response,
2948                                    model: model_telemetry_id,
2949                                    model_provider: model_provider_id.to_string(),
2950                                    response_latency,
2951                                    error_message,
2952                                    language_name: language_name.map(|name| name.to_proto()),
2953                                },
2954                                telemetry,
2955                                http_client,
2956                                model_api_key,
2957                                &executor,
2958                            );
2959
2960                            result?;
2961                            Ok(())
2962                        });
2963
2964                    while let Some((char_ops, line_ops)) = diff_rx.next().await {
2965                        codegen.update(&mut cx, |codegen, cx| {
2966                            codegen.last_equal_ranges.clear();
2967
2968                            let edits = char_ops
2969                                .into_iter()
2970                                .filter_map(|operation| match operation {
2971                                    CharOperation::Insert { text } => {
2972                                        let edit_start = snapshot.anchor_after(edit_start);
2973                                        Some((edit_start..edit_start, text))
2974                                    }
2975                                    CharOperation::Delete { bytes } => {
2976                                        let edit_end = edit_start + bytes;
2977                                        let edit_range = snapshot.anchor_after(edit_start)
2978                                            ..snapshot.anchor_before(edit_end);
2979                                        edit_start = edit_end;
2980                                        Some((edit_range, String::new()))
2981                                    }
2982                                    CharOperation::Keep { bytes } => {
2983                                        let edit_end = edit_start + bytes;
2984                                        let edit_range = snapshot.anchor_after(edit_start)
2985                                            ..snapshot.anchor_before(edit_end);
2986                                        edit_start = edit_end;
2987                                        codegen.last_equal_ranges.push(edit_range);
2988                                        None
2989                                    }
2990                                })
2991                                .collect::<Vec<_>>();
2992
2993                            if codegen.active {
2994                                codegen.apply_edits(edits.iter().cloned(), cx);
2995                                codegen.reapply_line_based_diff(line_ops.iter().cloned(), cx);
2996                            }
2997                            codegen.edits.extend(edits);
2998                            codegen.line_operations = line_ops;
2999                            codegen.edit_position = Some(snapshot.anchor_after(edit_start));
3000
3001                            cx.notify();
3002                        })?;
3003                    }
3004
3005                    // Streaming stopped and we have the new text in the buffer, and a line-based diff applied for the whole new buffer.
3006                    // That diff is not what a regular diff is and might look unexpected, ergo apply a regular diff.
3007                    // It's fine to apply even if the rest of the line diffing fails, as no more hunks are coming through `diff_rx`.
3008                    let batch_diff_task =
3009                        codegen.update(&mut cx, |codegen, cx| codegen.reapply_batch_diff(cx))?;
3010                    let (line_based_stream_diff, ()) =
3011                        join!(line_based_stream_diff, batch_diff_task);
3012                    line_based_stream_diff?;
3013
3014                    anyhow::Ok(())
3015                };
3016
3017                let result = generate.await;
3018                let elapsed_time = start_time.elapsed().as_secs_f64();
3019
3020                codegen
3021                    .update(&mut cx, |this, cx| {
3022                        this.message_id = message_id;
3023                        this.last_equal_ranges.clear();
3024                        if let Err(error) = result {
3025                            this.status = CodegenStatus::Error(error);
3026                        } else {
3027                            this.status = CodegenStatus::Done;
3028                        }
3029                        this.elapsed_time = Some(elapsed_time);
3030                        this.completion = Some(completion.lock().clone());
3031                        cx.emit(CodegenEvent::Finished);
3032                        cx.notify();
3033                    })
3034                    .ok();
3035            }
3036        });
3037        cx.notify();
3038    }
3039
3040    pub fn stop(&mut self, cx: &mut ModelContext<Self>) {
3041        self.last_equal_ranges.clear();
3042        if self.diff.is_empty() {
3043            self.status = CodegenStatus::Idle;
3044        } else {
3045            self.status = CodegenStatus::Done;
3046        }
3047        self.generation = Task::ready(());
3048        cx.emit(CodegenEvent::Finished);
3049        cx.notify();
3050    }
3051
3052    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
3053        self.buffer.update(cx, |buffer, cx| {
3054            if let Some(transaction_id) = self.transformation_transaction_id.take() {
3055                buffer.undo_transaction(transaction_id, cx);
3056                buffer.refresh_preview(cx);
3057            }
3058        });
3059    }
3060
3061    fn apply_edits(
3062        &mut self,
3063        edits: impl IntoIterator<Item = (Range<Anchor>, String)>,
3064        cx: &mut ModelContext<CodegenAlternative>,
3065    ) {
3066        let transaction = self.buffer.update(cx, |buffer, cx| {
3067            // Avoid grouping assistant edits with user edits.
3068            buffer.finalize_last_transaction(cx);
3069            buffer.start_transaction(cx);
3070            buffer.edit(edits, None, cx);
3071            buffer.end_transaction(cx)
3072        });
3073
3074        if let Some(transaction) = transaction {
3075            if let Some(first_transaction) = self.transformation_transaction_id {
3076                // Group all assistant edits into the first transaction.
3077                self.buffer.update(cx, |buffer, cx| {
3078                    buffer.merge_transactions(transaction, first_transaction, cx)
3079                });
3080            } else {
3081                self.transformation_transaction_id = Some(transaction);
3082                self.buffer
3083                    .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3084            }
3085        }
3086    }
3087
3088    fn reapply_line_based_diff(
3089        &mut self,
3090        line_operations: impl IntoIterator<Item = LineOperation>,
3091        cx: &mut ModelContext<Self>,
3092    ) {
3093        let old_snapshot = self.snapshot.clone();
3094        let old_range = self.range.to_point(&old_snapshot);
3095        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3096        let new_range = self.range.to_point(&new_snapshot);
3097
3098        let mut old_row = old_range.start.row;
3099        let mut new_row = new_range.start.row;
3100
3101        self.diff.deleted_row_ranges.clear();
3102        self.diff.inserted_row_ranges.clear();
3103        for operation in line_operations {
3104            match operation {
3105                LineOperation::Keep { lines } => {
3106                    old_row += lines;
3107                    new_row += lines;
3108                }
3109                LineOperation::Delete { lines } => {
3110                    let old_end_row = old_row + lines - 1;
3111                    let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3112
3113                    if let Some((_, last_deleted_row_range)) =
3114                        self.diff.deleted_row_ranges.last_mut()
3115                    {
3116                        if *last_deleted_row_range.end() + 1 == old_row {
3117                            *last_deleted_row_range = *last_deleted_row_range.start()..=old_end_row;
3118                        } else {
3119                            self.diff
3120                                .deleted_row_ranges
3121                                .push((new_row, old_row..=old_end_row));
3122                        }
3123                    } else {
3124                        self.diff
3125                            .deleted_row_ranges
3126                            .push((new_row, old_row..=old_end_row));
3127                    }
3128
3129                    old_row += lines;
3130                }
3131                LineOperation::Insert { lines } => {
3132                    let new_end_row = new_row + lines - 1;
3133                    let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3134                    let end = new_snapshot.anchor_before(Point::new(
3135                        new_end_row,
3136                        new_snapshot.line_len(MultiBufferRow(new_end_row)),
3137                    ));
3138                    self.diff.inserted_row_ranges.push(start..end);
3139                    new_row += lines;
3140                }
3141            }
3142
3143            cx.notify();
3144        }
3145    }
3146
3147    fn reapply_batch_diff(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
3148        let old_snapshot = self.snapshot.clone();
3149        let old_range = self.range.to_point(&old_snapshot);
3150        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3151        let new_range = self.range.to_point(&new_snapshot);
3152
3153        cx.spawn(|codegen, mut cx| async move {
3154            let (deleted_row_ranges, inserted_row_ranges) = cx
3155                .background_executor()
3156                .spawn(async move {
3157                    let old_text = old_snapshot
3158                        .text_for_range(
3159                            Point::new(old_range.start.row, 0)
3160                                ..Point::new(
3161                                    old_range.end.row,
3162                                    old_snapshot.line_len(MultiBufferRow(old_range.end.row)),
3163                                ),
3164                        )
3165                        .collect::<String>();
3166                    let new_text = new_snapshot
3167                        .text_for_range(
3168                            Point::new(new_range.start.row, 0)
3169                                ..Point::new(
3170                                    new_range.end.row,
3171                                    new_snapshot.line_len(MultiBufferRow(new_range.end.row)),
3172                                ),
3173                        )
3174                        .collect::<String>();
3175
3176                    let mut old_row = old_range.start.row;
3177                    let mut new_row = new_range.start.row;
3178                    let batch_diff =
3179                        similar::TextDiff::from_lines(old_text.as_str(), new_text.as_str());
3180
3181                    let mut deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)> = Vec::new();
3182                    let mut inserted_row_ranges = Vec::new();
3183                    for change in batch_diff.iter_all_changes() {
3184                        let line_count = change.value().lines().count() as u32;
3185                        match change.tag() {
3186                            similar::ChangeTag::Equal => {
3187                                old_row += line_count;
3188                                new_row += line_count;
3189                            }
3190                            similar::ChangeTag::Delete => {
3191                                let old_end_row = old_row + line_count - 1;
3192                                let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3193
3194                                if let Some((_, last_deleted_row_range)) =
3195                                    deleted_row_ranges.last_mut()
3196                                {
3197                                    if *last_deleted_row_range.end() + 1 == old_row {
3198                                        *last_deleted_row_range =
3199                                            *last_deleted_row_range.start()..=old_end_row;
3200                                    } else {
3201                                        deleted_row_ranges.push((new_row, old_row..=old_end_row));
3202                                    }
3203                                } else {
3204                                    deleted_row_ranges.push((new_row, old_row..=old_end_row));
3205                                }
3206
3207                                old_row += line_count;
3208                            }
3209                            similar::ChangeTag::Insert => {
3210                                let new_end_row = new_row + line_count - 1;
3211                                let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3212                                let end = new_snapshot.anchor_before(Point::new(
3213                                    new_end_row,
3214                                    new_snapshot.line_len(MultiBufferRow(new_end_row)),
3215                                ));
3216                                inserted_row_ranges.push(start..end);
3217                                new_row += line_count;
3218                            }
3219                        }
3220                    }
3221
3222                    (deleted_row_ranges, inserted_row_ranges)
3223                })
3224                .await;
3225
3226            codegen
3227                .update(&mut cx, |codegen, cx| {
3228                    codegen.diff.deleted_row_ranges = deleted_row_ranges;
3229                    codegen.diff.inserted_row_ranges = inserted_row_ranges;
3230                    cx.notify();
3231                })
3232                .ok();
3233        })
3234    }
3235}
3236
3237struct StripInvalidSpans<T> {
3238    stream: T,
3239    stream_done: bool,
3240    buffer: String,
3241    first_line: bool,
3242    line_end: bool,
3243    starts_with_code_block: bool,
3244}
3245
3246impl<T> StripInvalidSpans<T>
3247where
3248    T: Stream<Item = Result<String>>,
3249{
3250    fn new(stream: T) -> Self {
3251        Self {
3252            stream,
3253            stream_done: false,
3254            buffer: String::new(),
3255            first_line: true,
3256            line_end: false,
3257            starts_with_code_block: false,
3258        }
3259    }
3260}
3261
3262impl<T> Stream for StripInvalidSpans<T>
3263where
3264    T: Stream<Item = Result<String>>,
3265{
3266    type Item = Result<String>;
3267
3268    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Option<Self::Item>> {
3269        const CODE_BLOCK_DELIMITER: &str = "```";
3270        const CURSOR_SPAN: &str = "<|CURSOR|>";
3271
3272        let this = unsafe { self.get_unchecked_mut() };
3273        loop {
3274            if !this.stream_done {
3275                let mut stream = unsafe { Pin::new_unchecked(&mut this.stream) };
3276                match stream.as_mut().poll_next(cx) {
3277                    Poll::Ready(Some(Ok(chunk))) => {
3278                        this.buffer.push_str(&chunk);
3279                    }
3280                    Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
3281                    Poll::Ready(None) => {
3282                        this.stream_done = true;
3283                    }
3284                    Poll::Pending => return Poll::Pending,
3285                }
3286            }
3287
3288            let mut chunk = String::new();
3289            let mut consumed = 0;
3290            if !this.buffer.is_empty() {
3291                let mut lines = this.buffer.split('\n').enumerate().peekable();
3292                while let Some((line_ix, line)) = lines.next() {
3293                    if line_ix > 0 {
3294                        this.first_line = false;
3295                    }
3296
3297                    if this.first_line {
3298                        let trimmed_line = line.trim();
3299                        if lines.peek().is_some() {
3300                            if trimmed_line.starts_with(CODE_BLOCK_DELIMITER) {
3301                                consumed += line.len() + 1;
3302                                this.starts_with_code_block = true;
3303                                continue;
3304                            }
3305                        } else if trimmed_line.is_empty()
3306                            || prefixes(CODE_BLOCK_DELIMITER)
3307                                .any(|prefix| trimmed_line.starts_with(prefix))
3308                        {
3309                            break;
3310                        }
3311                    }
3312
3313                    let line_without_cursor = line.replace(CURSOR_SPAN, "");
3314                    if lines.peek().is_some() {
3315                        if this.line_end {
3316                            chunk.push('\n');
3317                        }
3318
3319                        chunk.push_str(&line_without_cursor);
3320                        this.line_end = true;
3321                        consumed += line.len() + 1;
3322                    } else if this.stream_done {
3323                        if !this.starts_with_code_block
3324                            || !line_without_cursor.trim().ends_with(CODE_BLOCK_DELIMITER)
3325                        {
3326                            if this.line_end {
3327                                chunk.push('\n');
3328                            }
3329
3330                            chunk.push_str(&line);
3331                        }
3332
3333                        consumed += line.len();
3334                    } else {
3335                        let trimmed_line = line.trim();
3336                        if trimmed_line.is_empty()
3337                            || prefixes(CURSOR_SPAN).any(|prefix| trimmed_line.ends_with(prefix))
3338                            || prefixes(CODE_BLOCK_DELIMITER)
3339                                .any(|prefix| trimmed_line.ends_with(prefix))
3340                        {
3341                            break;
3342                        } else {
3343                            if this.line_end {
3344                                chunk.push('\n');
3345                                this.line_end = false;
3346                            }
3347
3348                            chunk.push_str(&line_without_cursor);
3349                            consumed += line.len();
3350                        }
3351                    }
3352                }
3353            }
3354
3355            this.buffer = this.buffer.split_off(consumed);
3356            if !chunk.is_empty() {
3357                return Poll::Ready(Some(Ok(chunk)));
3358            } else if this.stream_done {
3359                return Poll::Ready(None);
3360            }
3361        }
3362    }
3363}
3364
3365struct AssistantCodeActionProvider {
3366    editor: WeakView<Editor>,
3367    workspace: WeakView<Workspace>,
3368    thread_store: Option<WeakModel<ThreadStore>>,
3369}
3370
3371impl CodeActionProvider for AssistantCodeActionProvider {
3372    fn code_actions(
3373        &self,
3374        buffer: &Model<Buffer>,
3375        range: Range<text::Anchor>,
3376        cx: &mut WindowContext,
3377    ) -> Task<Result<Vec<CodeAction>>> {
3378        if !AssistantSettings::get_global(cx).enabled {
3379            return Task::ready(Ok(Vec::new()));
3380        }
3381
3382        let snapshot = buffer.read(cx).snapshot();
3383        let mut range = range.to_point(&snapshot);
3384
3385        // Expand the range to line boundaries.
3386        range.start.column = 0;
3387        range.end.column = snapshot.line_len(range.end.row);
3388
3389        let mut has_diagnostics = false;
3390        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
3391            range.start = cmp::min(range.start, diagnostic.range.start);
3392            range.end = cmp::max(range.end, diagnostic.range.end);
3393            has_diagnostics = true;
3394        }
3395        if has_diagnostics {
3396            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
3397                if let Some(symbol) = symbols_containing_start.last() {
3398                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3399                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3400                }
3401            }
3402
3403            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
3404                if let Some(symbol) = symbols_containing_end.last() {
3405                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3406                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3407                }
3408            }
3409
3410            Task::ready(Ok(vec![CodeAction {
3411                server_id: language::LanguageServerId(0),
3412                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
3413                lsp_action: lsp::CodeAction {
3414                    title: "Fix with Assistant".into(),
3415                    ..Default::default()
3416                },
3417            }]))
3418        } else {
3419            Task::ready(Ok(Vec::new()))
3420        }
3421    }
3422
3423    fn apply_code_action(
3424        &self,
3425        buffer: Model<Buffer>,
3426        action: CodeAction,
3427        excerpt_id: ExcerptId,
3428        _push_to_history: bool,
3429        cx: &mut WindowContext,
3430    ) -> Task<Result<ProjectTransaction>> {
3431        let editor = self.editor.clone();
3432        let workspace = self.workspace.clone();
3433        let thread_store = self.thread_store.clone();
3434        cx.spawn(|mut cx| async move {
3435            let editor = editor.upgrade().context("editor was released")?;
3436            let range = editor
3437                .update(&mut cx, |editor, cx| {
3438                    editor.buffer().update(cx, |multibuffer, cx| {
3439                        let buffer = buffer.read(cx);
3440                        let multibuffer_snapshot = multibuffer.read(cx);
3441
3442                        let old_context_range =
3443                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
3444                        let mut new_context_range = old_context_range.clone();
3445                        if action
3446                            .range
3447                            .start
3448                            .cmp(&old_context_range.start, buffer)
3449                            .is_lt()
3450                        {
3451                            new_context_range.start = action.range.start;
3452                        }
3453                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
3454                            new_context_range.end = action.range.end;
3455                        }
3456                        drop(multibuffer_snapshot);
3457
3458                        if new_context_range != old_context_range {
3459                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
3460                        }
3461
3462                        let multibuffer_snapshot = multibuffer.read(cx);
3463                        Some(
3464                            multibuffer_snapshot
3465                                .anchor_in_excerpt(excerpt_id, action.range.start)?
3466                                ..multibuffer_snapshot
3467                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
3468                        )
3469                    })
3470                })?
3471                .context("invalid range")?;
3472
3473            cx.update_global(|assistant: &mut InlineAssistant, cx| {
3474                let assist_id = assistant.suggest_assist(
3475                    &editor,
3476                    range,
3477                    "Fix Diagnostics".into(),
3478                    None,
3479                    true,
3480                    workspace,
3481                    thread_store,
3482                    cx,
3483                );
3484                assistant.start_assist(assist_id, cx);
3485            })?;
3486
3487            Ok(ProjectTransaction::default())
3488        })
3489    }
3490}
3491
3492fn prefixes(text: &str) -> impl Iterator<Item = &str> {
3493    (0..text.len() - 1).map(|ix| &text[..ix + 1])
3494}
3495
3496fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3497    ranges.sort_unstable_by(|a, b| {
3498        a.start
3499            .cmp(&b.start, buffer)
3500            .then_with(|| b.end.cmp(&a.end, buffer))
3501    });
3502
3503    let mut ix = 0;
3504    while ix + 1 < ranges.len() {
3505        let b = ranges[ix + 1].clone();
3506        let a = &mut ranges[ix];
3507        if a.end.cmp(&b.start, buffer).is_gt() {
3508            if a.end.cmp(&b.end, buffer).is_lt() {
3509                a.end = b.end;
3510            }
3511            ranges.remove(ix + 1);
3512        } else {
3513            ix += 1;
3514        }
3515    }
3516}
3517
3518#[cfg(test)]
3519mod tests {
3520    use super::*;
3521    use futures::stream::{self};
3522    use gpui::{Context, TestAppContext};
3523    use indoc::indoc;
3524    use language::{
3525        language_settings, tree_sitter_rust, Buffer, Language, LanguageConfig, LanguageMatcher,
3526        Point,
3527    };
3528    use language_model::LanguageModelRegistry;
3529    use rand::prelude::*;
3530    use serde::Serialize;
3531    use settings::SettingsStore;
3532    use std::{future, sync::Arc};
3533
3534    #[derive(Serialize)]
3535    pub struct DummyCompletionRequest {
3536        pub name: String,
3537    }
3538
3539    #[gpui::test(iterations = 10)]
3540    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
3541        cx.set_global(cx.update(SettingsStore::test));
3542        cx.update(language_model::LanguageModelRegistry::test);
3543        cx.update(language_settings::init);
3544
3545        let text = indoc! {"
3546            fn main() {
3547                let x = 0;
3548                for _ in 0..10 {
3549                    x += 1;
3550                }
3551            }
3552        "};
3553        let buffer =
3554            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3555        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3556        let range = buffer.read_with(cx, |buffer, cx| {
3557            let snapshot = buffer.snapshot(cx);
3558            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
3559        });
3560        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3561        let codegen = cx.new_model(|cx| {
3562            CodegenAlternative::new(
3563                buffer.clone(),
3564                range.clone(),
3565                true,
3566                None,
3567                None,
3568                prompt_builder,
3569                cx,
3570            )
3571        });
3572
3573        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3574
3575        let mut new_text = concat!(
3576            "       let mut x = 0;\n",
3577            "       while x < 10 {\n",
3578            "           x += 1;\n",
3579            "       }",
3580        );
3581        while !new_text.is_empty() {
3582            let max_len = cmp::min(new_text.len(), 10);
3583            let len = rng.gen_range(1..=max_len);
3584            let (chunk, suffix) = new_text.split_at(len);
3585            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3586            new_text = suffix;
3587            cx.background_executor.run_until_parked();
3588        }
3589        drop(chunks_tx);
3590        cx.background_executor.run_until_parked();
3591
3592        assert_eq!(
3593            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3594            indoc! {"
3595                fn main() {
3596                    let mut x = 0;
3597                    while x < 10 {
3598                        x += 1;
3599                    }
3600                }
3601            "}
3602        );
3603    }
3604
3605    #[gpui::test(iterations = 10)]
3606    async fn test_autoindent_when_generating_past_indentation(
3607        cx: &mut TestAppContext,
3608        mut rng: StdRng,
3609    ) {
3610        cx.set_global(cx.update(SettingsStore::test));
3611        cx.update(language_settings::init);
3612
3613        let text = indoc! {"
3614            fn main() {
3615                le
3616            }
3617        "};
3618        let buffer =
3619            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3620        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3621        let range = buffer.read_with(cx, |buffer, cx| {
3622            let snapshot = buffer.snapshot(cx);
3623            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
3624        });
3625        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3626        let codegen = cx.new_model(|cx| {
3627            CodegenAlternative::new(
3628                buffer.clone(),
3629                range.clone(),
3630                true,
3631                None,
3632                None,
3633                prompt_builder,
3634                cx,
3635            )
3636        });
3637
3638        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3639
3640        cx.background_executor.run_until_parked();
3641
3642        let mut new_text = concat!(
3643            "t mut x = 0;\n",
3644            "while x < 10 {\n",
3645            "    x += 1;\n",
3646            "}", //
3647        );
3648        while !new_text.is_empty() {
3649            let max_len = cmp::min(new_text.len(), 10);
3650            let len = rng.gen_range(1..=max_len);
3651            let (chunk, suffix) = new_text.split_at(len);
3652            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3653            new_text = suffix;
3654            cx.background_executor.run_until_parked();
3655        }
3656        drop(chunks_tx);
3657        cx.background_executor.run_until_parked();
3658
3659        assert_eq!(
3660            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3661            indoc! {"
3662                fn main() {
3663                    let mut x = 0;
3664                    while x < 10 {
3665                        x += 1;
3666                    }
3667                }
3668            "}
3669        );
3670    }
3671
3672    #[gpui::test(iterations = 10)]
3673    async fn test_autoindent_when_generating_before_indentation(
3674        cx: &mut TestAppContext,
3675        mut rng: StdRng,
3676    ) {
3677        cx.update(LanguageModelRegistry::test);
3678        cx.set_global(cx.update(SettingsStore::test));
3679        cx.update(language_settings::init);
3680
3681        let text = concat!(
3682            "fn main() {\n",
3683            "  \n",
3684            "}\n" //
3685        );
3686        let buffer =
3687            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3688        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3689        let range = buffer.read_with(cx, |buffer, cx| {
3690            let snapshot = buffer.snapshot(cx);
3691            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
3692        });
3693        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3694        let codegen = cx.new_model(|cx| {
3695            CodegenAlternative::new(
3696                buffer.clone(),
3697                range.clone(),
3698                true,
3699                None,
3700                None,
3701                prompt_builder,
3702                cx,
3703            )
3704        });
3705
3706        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3707
3708        cx.background_executor.run_until_parked();
3709
3710        let mut new_text = concat!(
3711            "let mut x = 0;\n",
3712            "while x < 10 {\n",
3713            "    x += 1;\n",
3714            "}", //
3715        );
3716        while !new_text.is_empty() {
3717            let max_len = cmp::min(new_text.len(), 10);
3718            let len = rng.gen_range(1..=max_len);
3719            let (chunk, suffix) = new_text.split_at(len);
3720            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3721            new_text = suffix;
3722            cx.background_executor.run_until_parked();
3723        }
3724        drop(chunks_tx);
3725        cx.background_executor.run_until_parked();
3726
3727        assert_eq!(
3728            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3729            indoc! {"
3730                fn main() {
3731                    let mut x = 0;
3732                    while x < 10 {
3733                        x += 1;
3734                    }
3735                }
3736            "}
3737        );
3738    }
3739
3740    #[gpui::test(iterations = 10)]
3741    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
3742        cx.update(LanguageModelRegistry::test);
3743        cx.set_global(cx.update(SettingsStore::test));
3744        cx.update(language_settings::init);
3745
3746        let text = indoc! {"
3747            func main() {
3748            \tx := 0
3749            \tfor i := 0; i < 10; i++ {
3750            \t\tx++
3751            \t}
3752            }
3753        "};
3754        let buffer = cx.new_model(|cx| Buffer::local(text, cx));
3755        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3756        let range = buffer.read_with(cx, |buffer, cx| {
3757            let snapshot = buffer.snapshot(cx);
3758            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
3759        });
3760        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3761        let codegen = cx.new_model(|cx| {
3762            CodegenAlternative::new(
3763                buffer.clone(),
3764                range.clone(),
3765                true,
3766                None,
3767                None,
3768                prompt_builder,
3769                cx,
3770            )
3771        });
3772
3773        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3774        let new_text = concat!(
3775            "func main() {\n",
3776            "\tx := 0\n",
3777            "\tfor x < 10 {\n",
3778            "\t\tx++\n",
3779            "\t}", //
3780        );
3781        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
3782        drop(chunks_tx);
3783        cx.background_executor.run_until_parked();
3784
3785        assert_eq!(
3786            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3787            indoc! {"
3788                func main() {
3789                \tx := 0
3790                \tfor x < 10 {
3791                \t\tx++
3792                \t}
3793                }
3794            "}
3795        );
3796    }
3797
3798    #[gpui::test]
3799    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
3800        cx.update(LanguageModelRegistry::test);
3801        cx.set_global(cx.update(SettingsStore::test));
3802        cx.update(language_settings::init);
3803
3804        let text = indoc! {"
3805            fn main() {
3806                let x = 0;
3807            }
3808        "};
3809        let buffer =
3810            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3811        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3812        let range = buffer.read_with(cx, |buffer, cx| {
3813            let snapshot = buffer.snapshot(cx);
3814            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
3815        });
3816        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3817        let codegen = cx.new_model(|cx| {
3818            CodegenAlternative::new(
3819                buffer.clone(),
3820                range.clone(),
3821                false,
3822                None,
3823                None,
3824                prompt_builder,
3825                cx,
3826            )
3827        });
3828
3829        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3830        chunks_tx
3831            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
3832            .unwrap();
3833        drop(chunks_tx);
3834        cx.run_until_parked();
3835
3836        // The codegen is inactive, so the buffer doesn't get modified.
3837        assert_eq!(
3838            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3839            text
3840        );
3841
3842        // Activating the codegen applies the changes.
3843        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
3844        assert_eq!(
3845            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3846            indoc! {"
3847                fn main() {
3848                    let mut x = 0;
3849                    x += 1;
3850                }
3851            "}
3852        );
3853
3854        // Deactivating the codegen undoes the changes.
3855        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
3856        cx.run_until_parked();
3857        assert_eq!(
3858            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3859            text
3860        );
3861    }
3862
3863    #[gpui::test]
3864    async fn test_strip_invalid_spans_from_codeblock() {
3865        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
3866        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
3867        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
3868        assert_chunks(
3869            "```html\n```js\nLorem ipsum dolor\n```\n```",
3870            "```js\nLorem ipsum dolor\n```",
3871        )
3872        .await;
3873        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
3874        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
3875        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
3876        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
3877
3878        async fn assert_chunks(text: &str, expected_text: &str) {
3879            for chunk_size in 1..=text.len() {
3880                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
3881                    .map(|chunk| chunk.unwrap())
3882                    .collect::<String>()
3883                    .await;
3884                assert_eq!(
3885                    actual_text, expected_text,
3886                    "failed to strip invalid spans, chunk size: {}",
3887                    chunk_size
3888                );
3889            }
3890        }
3891
3892        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
3893            stream::iter(
3894                text.chars()
3895                    .collect::<Vec<_>>()
3896                    .chunks(size)
3897                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
3898                    .collect::<Vec<_>>(),
3899            )
3900        }
3901    }
3902
3903    fn simulate_response_stream(
3904        codegen: Model<CodegenAlternative>,
3905        cx: &mut TestAppContext,
3906    ) -> mpsc::UnboundedSender<String> {
3907        let (chunks_tx, chunks_rx) = mpsc::unbounded();
3908        codegen.update(cx, |codegen, cx| {
3909            codegen.handle_stream(
3910                String::new(),
3911                String::new(),
3912                None,
3913                future::ready(Ok(LanguageModelTextStream {
3914                    message_id: None,
3915                    stream: chunks_rx.map(Ok).boxed(),
3916                })),
3917                cx,
3918            );
3919        });
3920        chunks_tx
3921    }
3922
3923    fn rust_lang() -> Language {
3924        Language::new(
3925            LanguageConfig {
3926                name: "Rust".into(),
3927                matcher: LanguageMatcher {
3928                    path_suffixes: vec!["rs".to_string()],
3929                    ..Default::default()
3930                },
3931                ..Default::default()
3932            },
3933            Some(tree_sitter_rust::LANGUAGE.into()),
3934        )
3935        .with_indents_query(
3936            r#"
3937            (call_expression) @indent
3938            (field_expression) @indent
3939            (_ "(" ")" @end) @indent
3940            (_ "{" "}" @end) @indent
3941            "#,
3942        )
3943        .unwrap()
3944    }
3945}