inline_assistant.rs

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