inline_assistant.rs

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