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    message_id: Option<String>,
2566}
2567
2568enum CodegenStatus {
2569    Idle,
2570    Pending,
2571    Done,
2572    Error(anyhow::Error),
2573}
2574
2575#[derive(Default)]
2576struct Diff {
2577    deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
2578    inserted_row_ranges: Vec<Range<Anchor>>,
2579}
2580
2581impl Diff {
2582    fn is_empty(&self) -> bool {
2583        self.deleted_row_ranges.is_empty() && self.inserted_row_ranges.is_empty()
2584    }
2585}
2586
2587impl EventEmitter<CodegenEvent> for CodegenAlternative {}
2588
2589impl CodegenAlternative {
2590    pub fn new(
2591        buffer: Model<MultiBuffer>,
2592        range: Range<Anchor>,
2593        active: bool,
2594        telemetry: Option<Arc<Telemetry>>,
2595        builder: Arc<PromptBuilder>,
2596        cx: &mut ModelContext<Self>,
2597    ) -> Self {
2598        let snapshot = buffer.read(cx).snapshot(cx);
2599
2600        let (old_buffer, _, _) = buffer
2601            .read(cx)
2602            .range_to_buffer_ranges(range.clone(), cx)
2603            .pop()
2604            .unwrap();
2605        let old_buffer = cx.new_model(|cx| {
2606            let old_buffer = old_buffer.read(cx);
2607            let text = old_buffer.as_rope().clone();
2608            let line_ending = old_buffer.line_ending();
2609            let language = old_buffer.language().cloned();
2610            let language_registry = old_buffer.language_registry();
2611
2612            let mut buffer = Buffer::local_normalized(text, line_ending, cx);
2613            buffer.set_language(language, cx);
2614            if let Some(language_registry) = language_registry {
2615                buffer.set_language_registry(language_registry)
2616            }
2617            buffer
2618        });
2619
2620        Self {
2621            buffer: buffer.clone(),
2622            old_buffer,
2623            edit_position: None,
2624            message_id: None,
2625            snapshot,
2626            last_equal_ranges: Default::default(),
2627            transformation_transaction_id: None,
2628            status: CodegenStatus::Idle,
2629            generation: Task::ready(()),
2630            diff: Diff::default(),
2631            telemetry,
2632            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
2633            builder,
2634            active,
2635            edits: Vec::new(),
2636            line_operations: Vec::new(),
2637            range,
2638            request: None,
2639            elapsed_time: None,
2640        }
2641    }
2642
2643    fn set_active(&mut self, active: bool, cx: &mut ModelContext<Self>) {
2644        if active != self.active {
2645            self.active = active;
2646
2647            if self.active {
2648                let edits = self.edits.clone();
2649                self.apply_edits(edits, cx);
2650                if matches!(self.status, CodegenStatus::Pending) {
2651                    let line_operations = self.line_operations.clone();
2652                    self.reapply_line_based_diff(line_operations, cx);
2653                } else {
2654                    self.reapply_batch_diff(cx).detach();
2655                }
2656            } else if let Some(transaction_id) = self.transformation_transaction_id.take() {
2657                self.buffer.update(cx, |buffer, cx| {
2658                    buffer.undo_transaction(transaction_id, cx);
2659                    buffer.forget_transaction(transaction_id, cx);
2660                });
2661            }
2662        }
2663    }
2664
2665    fn handle_buffer_event(
2666        &mut self,
2667        _buffer: Model<MultiBuffer>,
2668        event: &multi_buffer::Event,
2669        cx: &mut ModelContext<Self>,
2670    ) {
2671        if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
2672            if self.transformation_transaction_id == Some(*transaction_id) {
2673                self.transformation_transaction_id = None;
2674                self.generation = Task::ready(());
2675                cx.emit(CodegenEvent::Undone);
2676            }
2677        }
2678    }
2679
2680    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
2681        &self.last_equal_ranges
2682    }
2683
2684    pub fn count_tokens(
2685        &self,
2686        user_prompt: String,
2687        assistant_panel_context: Option<LanguageModelRequest>,
2688        cx: &AppContext,
2689    ) -> BoxFuture<'static, Result<TokenCounts>> {
2690        if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
2691            let request = self.build_request(user_prompt, assistant_panel_context.clone(), cx);
2692            match request {
2693                Ok(request) => {
2694                    let total_count = model.count_tokens(request.clone(), cx);
2695                    let assistant_panel_count = assistant_panel_context
2696                        .map(|context| model.count_tokens(context, cx))
2697                        .unwrap_or_else(|| future::ready(Ok(0)).boxed());
2698
2699                    async move {
2700                        Ok(TokenCounts {
2701                            total: total_count.await?,
2702                            assistant_panel: assistant_panel_count.await?,
2703                        })
2704                    }
2705                    .boxed()
2706                }
2707                Err(error) => futures::future::ready(Err(error)).boxed(),
2708            }
2709        } else {
2710            future::ready(Err(anyhow!("no active model"))).boxed()
2711        }
2712    }
2713
2714    pub fn start(
2715        &mut self,
2716        user_prompt: String,
2717        assistant_panel_context: Option<LanguageModelRequest>,
2718        model: Arc<dyn LanguageModel>,
2719        cx: &mut ModelContext<Self>,
2720    ) -> Result<()> {
2721        if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
2722            self.buffer.update(cx, |buffer, cx| {
2723                buffer.undo_transaction(transformation_transaction_id, cx);
2724            });
2725        }
2726
2727        self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
2728
2729        let api_key = model.api_key(cx);
2730        let telemetry_id = model.telemetry_id();
2731        let provider_id = model.provider_id();
2732        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
2733            if user_prompt.trim().to_lowercase() == "delete" {
2734                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
2735            } else {
2736                let request = self.build_request(user_prompt, assistant_panel_context, cx)?;
2737                self.request = Some(request.clone());
2738
2739                cx.spawn(|_, cx| async move { model.stream_completion_text(request, &cx).await })
2740                    .boxed_local()
2741            };
2742        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
2743        Ok(())
2744    }
2745
2746    fn build_request(
2747        &self,
2748        user_prompt: String,
2749        assistant_panel_context: Option<LanguageModelRequest>,
2750        cx: &AppContext,
2751    ) -> Result<LanguageModelRequest> {
2752        let buffer = self.buffer.read(cx).snapshot(cx);
2753        let language = buffer.language_at(self.range.start);
2754        let language_name = if let Some(language) = language.as_ref() {
2755            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
2756                None
2757            } else {
2758                Some(language.name())
2759            }
2760        } else {
2761            None
2762        };
2763
2764        let language_name = language_name.as_ref();
2765        let start = buffer.point_to_buffer_offset(self.range.start);
2766        let end = buffer.point_to_buffer_offset(self.range.end);
2767        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
2768            let (start_buffer, start_buffer_offset) = start;
2769            let (end_buffer, end_buffer_offset) = end;
2770            if start_buffer.remote_id() == end_buffer.remote_id() {
2771                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
2772            } else {
2773                return Err(anyhow::anyhow!("invalid transformation range"));
2774            }
2775        } else {
2776            return Err(anyhow::anyhow!("invalid transformation range"));
2777        };
2778
2779        let prompt = self
2780            .builder
2781            .generate_inline_transformation_prompt(user_prompt, language_name, buffer, range)
2782            .map_err(|e| anyhow::anyhow!("Failed to generate content prompt: {}", e))?;
2783
2784        let mut messages = Vec::new();
2785        if let Some(context_request) = assistant_panel_context {
2786            messages = context_request.messages;
2787        }
2788
2789        messages.push(LanguageModelRequestMessage {
2790            role: Role::User,
2791            content: vec![prompt.into()],
2792            cache: false,
2793        });
2794
2795        Ok(LanguageModelRequest {
2796            messages,
2797            tools: Vec::new(),
2798            stop: Vec::new(),
2799            temperature: None,
2800        })
2801    }
2802
2803    pub fn handle_stream(
2804        &mut self,
2805        model_telemetry_id: String,
2806        model_provider_id: String,
2807        model_api_key: Option<String>,
2808        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
2809        cx: &mut ModelContext<Self>,
2810    ) {
2811        let start_time = Instant::now();
2812        let snapshot = self.snapshot.clone();
2813        let selected_text = snapshot
2814            .text_for_range(self.range.start..self.range.end)
2815            .collect::<Rope>();
2816
2817        let selection_start = self.range.start.to_point(&snapshot);
2818
2819        // Start with the indentation of the first line in the selection
2820        let mut suggested_line_indent = snapshot
2821            .suggested_indents(selection_start.row..=selection_start.row, cx)
2822            .into_values()
2823            .next()
2824            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
2825
2826        // If the first line in the selection does not have indentation, check the following lines
2827        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
2828            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
2829                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
2830                // Prefer tabs if a line in the selection uses tabs as indentation
2831                if line_indent.kind == IndentKind::Tab {
2832                    suggested_line_indent.kind = IndentKind::Tab;
2833                    break;
2834                }
2835            }
2836        }
2837
2838        let http_client = cx.http_client().clone();
2839        let telemetry = self.telemetry.clone();
2840        let language_name = {
2841            let multibuffer = self.buffer.read(cx);
2842            let ranges = multibuffer.range_to_buffer_ranges(self.range.clone(), cx);
2843            ranges
2844                .first()
2845                .and_then(|(buffer, _, _)| buffer.read(cx).language())
2846                .map(|language| language.name())
2847        };
2848
2849        self.diff = Diff::default();
2850        self.status = CodegenStatus::Pending;
2851        let mut edit_start = self.range.start.to_offset(&snapshot);
2852        self.generation = cx.spawn(|codegen, mut cx| {
2853            async move {
2854                let stream = stream.await;
2855                let message_id = stream
2856                    .as_ref()
2857                    .ok()
2858                    .and_then(|stream| stream.message_id.clone());
2859                let generate = async {
2860                    let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
2861                    let executor = cx.background_executor().clone();
2862                    let message_id = message_id.clone();
2863                    let line_based_stream_diff: Task<anyhow::Result<()>> =
2864                        cx.background_executor().spawn(async move {
2865                            let mut response_latency = None;
2866                            let request_start = Instant::now();
2867                            let diff = async {
2868                                let chunks = StripInvalidSpans::new(stream?.stream);
2869                                futures::pin_mut!(chunks);
2870                                let mut diff = StreamingDiff::new(selected_text.to_string());
2871                                let mut line_diff = LineDiff::default();
2872
2873                                let mut new_text = String::new();
2874                                let mut base_indent = None;
2875                                let mut line_indent = None;
2876                                let mut first_line = true;
2877
2878                                while let Some(chunk) = chunks.next().await {
2879                                    if response_latency.is_none() {
2880                                        response_latency = Some(request_start.elapsed());
2881                                    }
2882                                    let chunk = chunk?;
2883
2884                                    let mut lines = chunk.split('\n').peekable();
2885                                    while let Some(line) = lines.next() {
2886                                        new_text.push_str(line);
2887                                        if line_indent.is_none() {
2888                                            if let Some(non_whitespace_ch_ix) =
2889                                                new_text.find(|ch: char| !ch.is_whitespace())
2890                                            {
2891                                                line_indent = Some(non_whitespace_ch_ix);
2892                                                base_indent = base_indent.or(line_indent);
2893
2894                                                let line_indent = line_indent.unwrap();
2895                                                let base_indent = base_indent.unwrap();
2896                                                let indent_delta =
2897                                                    line_indent as i32 - base_indent as i32;
2898                                                let mut corrected_indent_len = cmp::max(
2899                                                    0,
2900                                                    suggested_line_indent.len as i32 + indent_delta,
2901                                                )
2902                                                    as usize;
2903                                                if first_line {
2904                                                    corrected_indent_len = corrected_indent_len
2905                                                        .saturating_sub(
2906                                                            selection_start.column as usize,
2907                                                        );
2908                                                }
2909
2910                                                let indent_char = suggested_line_indent.char();
2911                                                let mut indent_buffer = [0; 4];
2912                                                let indent_str =
2913                                                    indent_char.encode_utf8(&mut indent_buffer);
2914                                                new_text.replace_range(
2915                                                    ..line_indent,
2916                                                    &indent_str.repeat(corrected_indent_len),
2917                                                );
2918                                            }
2919                                        }
2920
2921                                        if line_indent.is_some() {
2922                                            let char_ops = diff.push_new(&new_text);
2923                                            line_diff
2924                                                .push_char_operations(&char_ops, &selected_text);
2925                                            diff_tx
2926                                                .send((char_ops, line_diff.line_operations()))
2927                                                .await?;
2928                                            new_text.clear();
2929                                        }
2930
2931                                        if lines.peek().is_some() {
2932                                            let char_ops = diff.push_new("\n");
2933                                            line_diff
2934                                                .push_char_operations(&char_ops, &selected_text);
2935                                            diff_tx
2936                                                .send((char_ops, line_diff.line_operations()))
2937                                                .await?;
2938                                            if line_indent.is_none() {
2939                                                // Don't write out the leading indentation in empty lines on the next line
2940                                                // This is the case where the above if statement didn't clear the buffer
2941                                                new_text.clear();
2942                                            }
2943                                            line_indent = None;
2944                                            first_line = false;
2945                                        }
2946                                    }
2947                                }
2948
2949                                let mut char_ops = diff.push_new(&new_text);
2950                                char_ops.extend(diff.finish());
2951                                line_diff.push_char_operations(&char_ops, &selected_text);
2952                                line_diff.finish(&selected_text);
2953                                diff_tx
2954                                    .send((char_ops, line_diff.line_operations()))
2955                                    .await?;
2956
2957                                anyhow::Ok(())
2958                            };
2959
2960                            let result = diff.await;
2961
2962                            let error_message =
2963                                result.as_ref().err().map(|error| error.to_string());
2964                            report_assistant_event(
2965                                AssistantEvent {
2966                                    conversation_id: None,
2967                                    message_id,
2968                                    kind: AssistantKind::Inline,
2969                                    phase: AssistantPhase::Response,
2970                                    model: model_telemetry_id,
2971                                    model_provider: model_provider_id.to_string(),
2972                                    response_latency,
2973                                    error_message,
2974                                    language_name: language_name.map(|name| name.to_proto()),
2975                                },
2976                                telemetry,
2977                                http_client,
2978                                model_api_key,
2979                                &executor,
2980                            );
2981
2982                            result?;
2983                            Ok(())
2984                        });
2985
2986                    while let Some((char_ops, line_ops)) = diff_rx.next().await {
2987                        codegen.update(&mut cx, |codegen, cx| {
2988                            codegen.last_equal_ranges.clear();
2989
2990                            let edits = char_ops
2991                                .into_iter()
2992                                .filter_map(|operation| match operation {
2993                                    CharOperation::Insert { text } => {
2994                                        let edit_start = snapshot.anchor_after(edit_start);
2995                                        Some((edit_start..edit_start, text))
2996                                    }
2997                                    CharOperation::Delete { bytes } => {
2998                                        let edit_end = edit_start + bytes;
2999                                        let edit_range = snapshot.anchor_after(edit_start)
3000                                            ..snapshot.anchor_before(edit_end);
3001                                        edit_start = edit_end;
3002                                        Some((edit_range, String::new()))
3003                                    }
3004                                    CharOperation::Keep { bytes } => {
3005                                        let edit_end = edit_start + bytes;
3006                                        let edit_range = snapshot.anchor_after(edit_start)
3007                                            ..snapshot.anchor_before(edit_end);
3008                                        edit_start = edit_end;
3009                                        codegen.last_equal_ranges.push(edit_range);
3010                                        None
3011                                    }
3012                                })
3013                                .collect::<Vec<_>>();
3014
3015                            if codegen.active {
3016                                codegen.apply_edits(edits.iter().cloned(), cx);
3017                                codegen.reapply_line_based_diff(line_ops.iter().cloned(), cx);
3018                            }
3019                            codegen.edits.extend(edits);
3020                            codegen.line_operations = line_ops;
3021                            codegen.edit_position = Some(snapshot.anchor_after(edit_start));
3022
3023                            cx.notify();
3024                        })?;
3025                    }
3026
3027                    // Streaming stopped and we have the new text in the buffer, and a line-based diff applied for the whole new buffer.
3028                    // That diff is not what a regular diff is and might look unexpected, ergo apply a regular diff.
3029                    // It's fine to apply even if the rest of the line diffing fails, as no more hunks are coming through `diff_rx`.
3030                    let batch_diff_task =
3031                        codegen.update(&mut cx, |codegen, cx| codegen.reapply_batch_diff(cx))?;
3032                    let (line_based_stream_diff, ()) =
3033                        join!(line_based_stream_diff, batch_diff_task);
3034                    line_based_stream_diff?;
3035
3036                    anyhow::Ok(())
3037                };
3038
3039                let result = generate.await;
3040                let elapsed_time = start_time.elapsed().as_secs_f64();
3041
3042                codegen
3043                    .update(&mut cx, |this, cx| {
3044                        this.message_id = message_id;
3045                        this.last_equal_ranges.clear();
3046                        if let Err(error) = result {
3047                            this.status = CodegenStatus::Error(error);
3048                        } else {
3049                            this.status = CodegenStatus::Done;
3050                        }
3051                        this.elapsed_time = Some(elapsed_time);
3052                        cx.emit(CodegenEvent::Finished);
3053                        cx.notify();
3054                    })
3055                    .ok();
3056            }
3057        });
3058        cx.notify();
3059    }
3060
3061    pub fn stop(&mut self, cx: &mut ModelContext<Self>) {
3062        self.last_equal_ranges.clear();
3063        if self.diff.is_empty() {
3064            self.status = CodegenStatus::Idle;
3065        } else {
3066            self.status = CodegenStatus::Done;
3067        }
3068        self.generation = Task::ready(());
3069        cx.emit(CodegenEvent::Finished);
3070        cx.notify();
3071    }
3072
3073    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
3074        self.buffer.update(cx, |buffer, cx| {
3075            if let Some(transaction_id) = self.transformation_transaction_id.take() {
3076                buffer.undo_transaction(transaction_id, cx);
3077                buffer.refresh_preview(cx);
3078            }
3079        });
3080    }
3081
3082    fn apply_edits(
3083        &mut self,
3084        edits: impl IntoIterator<Item = (Range<Anchor>, String)>,
3085        cx: &mut ModelContext<CodegenAlternative>,
3086    ) {
3087        let transaction = self.buffer.update(cx, |buffer, cx| {
3088            // Avoid grouping assistant edits with user edits.
3089            buffer.finalize_last_transaction(cx);
3090            buffer.start_transaction(cx);
3091            buffer.edit(edits, None, cx);
3092            buffer.end_transaction(cx)
3093        });
3094
3095        if let Some(transaction) = transaction {
3096            if let Some(first_transaction) = self.transformation_transaction_id {
3097                // Group all assistant edits into the first transaction.
3098                self.buffer.update(cx, |buffer, cx| {
3099                    buffer.merge_transactions(transaction, first_transaction, cx)
3100                });
3101            } else {
3102                self.transformation_transaction_id = Some(transaction);
3103                self.buffer
3104                    .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3105            }
3106        }
3107    }
3108
3109    fn reapply_line_based_diff(
3110        &mut self,
3111        line_operations: impl IntoIterator<Item = LineOperation>,
3112        cx: &mut ModelContext<Self>,
3113    ) {
3114        let old_snapshot = self.snapshot.clone();
3115        let old_range = self.range.to_point(&old_snapshot);
3116        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3117        let new_range = self.range.to_point(&new_snapshot);
3118
3119        let mut old_row = old_range.start.row;
3120        let mut new_row = new_range.start.row;
3121
3122        self.diff.deleted_row_ranges.clear();
3123        self.diff.inserted_row_ranges.clear();
3124        for operation in line_operations {
3125            match operation {
3126                LineOperation::Keep { lines } => {
3127                    old_row += lines;
3128                    new_row += lines;
3129                }
3130                LineOperation::Delete { lines } => {
3131                    let old_end_row = old_row + lines - 1;
3132                    let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3133
3134                    if let Some((_, last_deleted_row_range)) =
3135                        self.diff.deleted_row_ranges.last_mut()
3136                    {
3137                        if *last_deleted_row_range.end() + 1 == old_row {
3138                            *last_deleted_row_range = *last_deleted_row_range.start()..=old_end_row;
3139                        } else {
3140                            self.diff
3141                                .deleted_row_ranges
3142                                .push((new_row, old_row..=old_end_row));
3143                        }
3144                    } else {
3145                        self.diff
3146                            .deleted_row_ranges
3147                            .push((new_row, old_row..=old_end_row));
3148                    }
3149
3150                    old_row += lines;
3151                }
3152                LineOperation::Insert { lines } => {
3153                    let new_end_row = new_row + lines - 1;
3154                    let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3155                    let end = new_snapshot.anchor_before(Point::new(
3156                        new_end_row,
3157                        new_snapshot.line_len(MultiBufferRow(new_end_row)),
3158                    ));
3159                    self.diff.inserted_row_ranges.push(start..end);
3160                    new_row += lines;
3161                }
3162            }
3163
3164            cx.notify();
3165        }
3166    }
3167
3168    fn reapply_batch_diff(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
3169        let old_snapshot = self.snapshot.clone();
3170        let old_range = self.range.to_point(&old_snapshot);
3171        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3172        let new_range = self.range.to_point(&new_snapshot);
3173
3174        cx.spawn(|codegen, mut cx| async move {
3175            let (deleted_row_ranges, inserted_row_ranges) = cx
3176                .background_executor()
3177                .spawn(async move {
3178                    let old_text = old_snapshot
3179                        .text_for_range(
3180                            Point::new(old_range.start.row, 0)
3181                                ..Point::new(
3182                                    old_range.end.row,
3183                                    old_snapshot.line_len(MultiBufferRow(old_range.end.row)),
3184                                ),
3185                        )
3186                        .collect::<String>();
3187                    let new_text = new_snapshot
3188                        .text_for_range(
3189                            Point::new(new_range.start.row, 0)
3190                                ..Point::new(
3191                                    new_range.end.row,
3192                                    new_snapshot.line_len(MultiBufferRow(new_range.end.row)),
3193                                ),
3194                        )
3195                        .collect::<String>();
3196
3197                    let mut old_row = old_range.start.row;
3198                    let mut new_row = new_range.start.row;
3199                    let batch_diff =
3200                        similar::TextDiff::from_lines(old_text.as_str(), new_text.as_str());
3201
3202                    let mut deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)> = Vec::new();
3203                    let mut inserted_row_ranges = Vec::new();
3204                    for change in batch_diff.iter_all_changes() {
3205                        let line_count = change.value().lines().count() as u32;
3206                        match change.tag() {
3207                            similar::ChangeTag::Equal => {
3208                                old_row += line_count;
3209                                new_row += line_count;
3210                            }
3211                            similar::ChangeTag::Delete => {
3212                                let old_end_row = old_row + line_count - 1;
3213                                let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3214
3215                                if let Some((_, last_deleted_row_range)) =
3216                                    deleted_row_ranges.last_mut()
3217                                {
3218                                    if *last_deleted_row_range.end() + 1 == old_row {
3219                                        *last_deleted_row_range =
3220                                            *last_deleted_row_range.start()..=old_end_row;
3221                                    } else {
3222                                        deleted_row_ranges.push((new_row, old_row..=old_end_row));
3223                                    }
3224                                } else {
3225                                    deleted_row_ranges.push((new_row, old_row..=old_end_row));
3226                                }
3227
3228                                old_row += line_count;
3229                            }
3230                            similar::ChangeTag::Insert => {
3231                                let new_end_row = new_row + line_count - 1;
3232                                let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3233                                let end = new_snapshot.anchor_before(Point::new(
3234                                    new_end_row,
3235                                    new_snapshot.line_len(MultiBufferRow(new_end_row)),
3236                                ));
3237                                inserted_row_ranges.push(start..end);
3238                                new_row += line_count;
3239                            }
3240                        }
3241                    }
3242
3243                    (deleted_row_ranges, inserted_row_ranges)
3244                })
3245                .await;
3246
3247            codegen
3248                .update(&mut cx, |codegen, cx| {
3249                    codegen.diff.deleted_row_ranges = deleted_row_ranges;
3250                    codegen.diff.inserted_row_ranges = inserted_row_ranges;
3251                    cx.notify();
3252                })
3253                .ok();
3254        })
3255    }
3256}
3257
3258struct StripInvalidSpans<T> {
3259    stream: T,
3260    stream_done: bool,
3261    buffer: String,
3262    first_line: bool,
3263    line_end: bool,
3264    starts_with_code_block: bool,
3265}
3266
3267impl<T> StripInvalidSpans<T>
3268where
3269    T: Stream<Item = Result<String>>,
3270{
3271    fn new(stream: T) -> Self {
3272        Self {
3273            stream,
3274            stream_done: false,
3275            buffer: String::new(),
3276            first_line: true,
3277            line_end: false,
3278            starts_with_code_block: false,
3279        }
3280    }
3281}
3282
3283impl<T> Stream for StripInvalidSpans<T>
3284where
3285    T: Stream<Item = Result<String>>,
3286{
3287    type Item = Result<String>;
3288
3289    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Option<Self::Item>> {
3290        const CODE_BLOCK_DELIMITER: &str = "```";
3291        const CURSOR_SPAN: &str = "<|CURSOR|>";
3292
3293        let this = unsafe { self.get_unchecked_mut() };
3294        loop {
3295            if !this.stream_done {
3296                let mut stream = unsafe { Pin::new_unchecked(&mut this.stream) };
3297                match stream.as_mut().poll_next(cx) {
3298                    Poll::Ready(Some(Ok(chunk))) => {
3299                        this.buffer.push_str(&chunk);
3300                    }
3301                    Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
3302                    Poll::Ready(None) => {
3303                        this.stream_done = true;
3304                    }
3305                    Poll::Pending => return Poll::Pending,
3306                }
3307            }
3308
3309            let mut chunk = String::new();
3310            let mut consumed = 0;
3311            if !this.buffer.is_empty() {
3312                let mut lines = this.buffer.split('\n').enumerate().peekable();
3313                while let Some((line_ix, line)) = lines.next() {
3314                    if line_ix > 0 {
3315                        this.first_line = false;
3316                    }
3317
3318                    if this.first_line {
3319                        let trimmed_line = line.trim();
3320                        if lines.peek().is_some() {
3321                            if trimmed_line.starts_with(CODE_BLOCK_DELIMITER) {
3322                                consumed += line.len() + 1;
3323                                this.starts_with_code_block = true;
3324                                continue;
3325                            }
3326                        } else if trimmed_line.is_empty()
3327                            || prefixes(CODE_BLOCK_DELIMITER)
3328                                .any(|prefix| trimmed_line.starts_with(prefix))
3329                        {
3330                            break;
3331                        }
3332                    }
3333
3334                    let line_without_cursor = line.replace(CURSOR_SPAN, "");
3335                    if lines.peek().is_some() {
3336                        if this.line_end {
3337                            chunk.push('\n');
3338                        }
3339
3340                        chunk.push_str(&line_without_cursor);
3341                        this.line_end = true;
3342                        consumed += line.len() + 1;
3343                    } else if this.stream_done {
3344                        if !this.starts_with_code_block
3345                            || !line_without_cursor.trim().ends_with(CODE_BLOCK_DELIMITER)
3346                        {
3347                            if this.line_end {
3348                                chunk.push('\n');
3349                            }
3350
3351                            chunk.push_str(&line);
3352                        }
3353
3354                        consumed += line.len();
3355                    } else {
3356                        let trimmed_line = line.trim();
3357                        if trimmed_line.is_empty()
3358                            || prefixes(CURSOR_SPAN).any(|prefix| trimmed_line.ends_with(prefix))
3359                            || prefixes(CODE_BLOCK_DELIMITER)
3360                                .any(|prefix| trimmed_line.ends_with(prefix))
3361                        {
3362                            break;
3363                        } else {
3364                            if this.line_end {
3365                                chunk.push('\n');
3366                                this.line_end = false;
3367                            }
3368
3369                            chunk.push_str(&line_without_cursor);
3370                            consumed += line.len();
3371                        }
3372                    }
3373                }
3374            }
3375
3376            this.buffer = this.buffer.split_off(consumed);
3377            if !chunk.is_empty() {
3378                return Poll::Ready(Some(Ok(chunk)));
3379            } else if this.stream_done {
3380                return Poll::Ready(None);
3381            }
3382        }
3383    }
3384}
3385
3386struct AssistantCodeActionProvider {
3387    editor: WeakView<Editor>,
3388    workspace: WeakView<Workspace>,
3389}
3390
3391impl CodeActionProvider for AssistantCodeActionProvider {
3392    fn code_actions(
3393        &self,
3394        buffer: &Model<Buffer>,
3395        range: Range<text::Anchor>,
3396        cx: &mut WindowContext,
3397    ) -> Task<Result<Vec<CodeAction>>> {
3398        if !AssistantSettings::get_global(cx).enabled {
3399            return Task::ready(Ok(Vec::new()));
3400        }
3401
3402        let snapshot = buffer.read(cx).snapshot();
3403        let mut range = range.to_point(&snapshot);
3404
3405        // Expand the range to line boundaries.
3406        range.start.column = 0;
3407        range.end.column = snapshot.line_len(range.end.row);
3408
3409        let mut has_diagnostics = false;
3410        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
3411            range.start = cmp::min(range.start, diagnostic.range.start);
3412            range.end = cmp::max(range.end, diagnostic.range.end);
3413            has_diagnostics = true;
3414        }
3415        if has_diagnostics {
3416            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
3417                if let Some(symbol) = symbols_containing_start.last() {
3418                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3419                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3420                }
3421            }
3422
3423            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
3424                if let Some(symbol) = symbols_containing_end.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            Task::ready(Ok(vec![CodeAction {
3431                server_id: language::LanguageServerId(0),
3432                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
3433                lsp_action: lsp::CodeAction {
3434                    title: "Fix with Assistant".into(),
3435                    ..Default::default()
3436                },
3437            }]))
3438        } else {
3439            Task::ready(Ok(Vec::new()))
3440        }
3441    }
3442
3443    fn apply_code_action(
3444        &self,
3445        buffer: Model<Buffer>,
3446        action: CodeAction,
3447        excerpt_id: ExcerptId,
3448        _push_to_history: bool,
3449        cx: &mut WindowContext,
3450    ) -> Task<Result<ProjectTransaction>> {
3451        let editor = self.editor.clone();
3452        let workspace = self.workspace.clone();
3453        cx.spawn(|mut cx| async move {
3454            let editor = editor.upgrade().context("editor was released")?;
3455            let range = editor
3456                .update(&mut cx, |editor, cx| {
3457                    editor.buffer().update(cx, |multibuffer, cx| {
3458                        let buffer = buffer.read(cx);
3459                        let multibuffer_snapshot = multibuffer.read(cx);
3460
3461                        let old_context_range =
3462                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
3463                        let mut new_context_range = old_context_range.clone();
3464                        if action
3465                            .range
3466                            .start
3467                            .cmp(&old_context_range.start, buffer)
3468                            .is_lt()
3469                        {
3470                            new_context_range.start = action.range.start;
3471                        }
3472                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
3473                            new_context_range.end = action.range.end;
3474                        }
3475                        drop(multibuffer_snapshot);
3476
3477                        if new_context_range != old_context_range {
3478                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
3479                        }
3480
3481                        let multibuffer_snapshot = multibuffer.read(cx);
3482                        Some(
3483                            multibuffer_snapshot
3484                                .anchor_in_excerpt(excerpt_id, action.range.start)?
3485                                ..multibuffer_snapshot
3486                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
3487                        )
3488                    })
3489                })?
3490                .context("invalid range")?;
3491            let assistant_panel = workspace.update(&mut cx, |workspace, cx| {
3492                workspace
3493                    .panel::<AssistantPanel>(cx)
3494                    .context("assistant panel was released")
3495            })??;
3496
3497            cx.update_global(|assistant: &mut InlineAssistant, cx| {
3498                let assist_id = assistant.suggest_assist(
3499                    &editor,
3500                    range,
3501                    "Fix Diagnostics".into(),
3502                    None,
3503                    true,
3504                    Some(workspace),
3505                    Some(&assistant_panel),
3506                    cx,
3507                );
3508                assistant.start_assist(assist_id, cx);
3509            })?;
3510
3511            Ok(ProjectTransaction::default())
3512        })
3513    }
3514}
3515
3516fn prefixes(text: &str) -> impl Iterator<Item = &str> {
3517    (0..text.len() - 1).map(|ix| &text[..ix + 1])
3518}
3519
3520fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3521    ranges.sort_unstable_by(|a, b| {
3522        a.start
3523            .cmp(&b.start, buffer)
3524            .then_with(|| b.end.cmp(&a.end, buffer))
3525    });
3526
3527    let mut ix = 0;
3528    while ix + 1 < ranges.len() {
3529        let b = ranges[ix + 1].clone();
3530        let a = &mut ranges[ix];
3531        if a.end.cmp(&b.start, buffer).is_gt() {
3532            if a.end.cmp(&b.end, buffer).is_lt() {
3533                a.end = b.end;
3534            }
3535            ranges.remove(ix + 1);
3536        } else {
3537            ix += 1;
3538        }
3539    }
3540}
3541
3542#[cfg(test)]
3543mod tests {
3544    use super::*;
3545    use futures::stream::{self};
3546    use gpui::{Context, TestAppContext};
3547    use indoc::indoc;
3548    use language::{
3549        language_settings, tree_sitter_rust, Buffer, Language, LanguageConfig, LanguageMatcher,
3550        Point,
3551    };
3552    use language_model::LanguageModelRegistry;
3553    use rand::prelude::*;
3554    use serde::Serialize;
3555    use settings::SettingsStore;
3556    use std::{future, sync::Arc};
3557
3558    #[derive(Serialize)]
3559    pub struct DummyCompletionRequest {
3560        pub name: String,
3561    }
3562
3563    #[gpui::test(iterations = 10)]
3564    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
3565        cx.set_global(cx.update(SettingsStore::test));
3566        cx.update(language_model::LanguageModelRegistry::test);
3567        cx.update(language_settings::init);
3568
3569        let text = indoc! {"
3570            fn main() {
3571                let x = 0;
3572                for _ in 0..10 {
3573                    x += 1;
3574                }
3575            }
3576        "};
3577        let buffer =
3578            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3579        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3580        let range = buffer.read_with(cx, |buffer, cx| {
3581            let snapshot = buffer.snapshot(cx);
3582            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
3583        });
3584        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3585        let codegen = cx.new_model(|cx| {
3586            CodegenAlternative::new(
3587                buffer.clone(),
3588                range.clone(),
3589                true,
3590                None,
3591                prompt_builder,
3592                cx,
3593            )
3594        });
3595
3596        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3597
3598        let mut new_text = concat!(
3599            "       let mut x = 0;\n",
3600            "       while x < 10 {\n",
3601            "           x += 1;\n",
3602            "       }",
3603        );
3604        while !new_text.is_empty() {
3605            let max_len = cmp::min(new_text.len(), 10);
3606            let len = rng.gen_range(1..=max_len);
3607            let (chunk, suffix) = new_text.split_at(len);
3608            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3609            new_text = suffix;
3610            cx.background_executor.run_until_parked();
3611        }
3612        drop(chunks_tx);
3613        cx.background_executor.run_until_parked();
3614
3615        assert_eq!(
3616            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3617            indoc! {"
3618                fn main() {
3619                    let mut x = 0;
3620                    while x < 10 {
3621                        x += 1;
3622                    }
3623                }
3624            "}
3625        );
3626    }
3627
3628    #[gpui::test(iterations = 10)]
3629    async fn test_autoindent_when_generating_past_indentation(
3630        cx: &mut TestAppContext,
3631        mut rng: StdRng,
3632    ) {
3633        cx.set_global(cx.update(SettingsStore::test));
3634        cx.update(language_settings::init);
3635
3636        let text = indoc! {"
3637            fn main() {
3638                le
3639            }
3640        "};
3641        let buffer =
3642            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3643        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3644        let range = buffer.read_with(cx, |buffer, cx| {
3645            let snapshot = buffer.snapshot(cx);
3646            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
3647        });
3648        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3649        let codegen = cx.new_model(|cx| {
3650            CodegenAlternative::new(
3651                buffer.clone(),
3652                range.clone(),
3653                true,
3654                None,
3655                prompt_builder,
3656                cx,
3657            )
3658        });
3659
3660        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3661
3662        cx.background_executor.run_until_parked();
3663
3664        let mut new_text = concat!(
3665            "t mut x = 0;\n",
3666            "while x < 10 {\n",
3667            "    x += 1;\n",
3668            "}", //
3669        );
3670        while !new_text.is_empty() {
3671            let max_len = cmp::min(new_text.len(), 10);
3672            let len = rng.gen_range(1..=max_len);
3673            let (chunk, suffix) = new_text.split_at(len);
3674            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3675            new_text = suffix;
3676            cx.background_executor.run_until_parked();
3677        }
3678        drop(chunks_tx);
3679        cx.background_executor.run_until_parked();
3680
3681        assert_eq!(
3682            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3683            indoc! {"
3684                fn main() {
3685                    let mut x = 0;
3686                    while x < 10 {
3687                        x += 1;
3688                    }
3689                }
3690            "}
3691        );
3692    }
3693
3694    #[gpui::test(iterations = 10)]
3695    async fn test_autoindent_when_generating_before_indentation(
3696        cx: &mut TestAppContext,
3697        mut rng: StdRng,
3698    ) {
3699        cx.update(LanguageModelRegistry::test);
3700        cx.set_global(cx.update(SettingsStore::test));
3701        cx.update(language_settings::init);
3702
3703        let text = concat!(
3704            "fn main() {\n",
3705            "  \n",
3706            "}\n" //
3707        );
3708        let buffer =
3709            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3710        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3711        let range = buffer.read_with(cx, |buffer, cx| {
3712            let snapshot = buffer.snapshot(cx);
3713            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
3714        });
3715        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3716        let codegen = cx.new_model(|cx| {
3717            CodegenAlternative::new(
3718                buffer.clone(),
3719                range.clone(),
3720                true,
3721                None,
3722                prompt_builder,
3723                cx,
3724            )
3725        });
3726
3727        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3728
3729        cx.background_executor.run_until_parked();
3730
3731        let mut new_text = concat!(
3732            "let mut x = 0;\n",
3733            "while x < 10 {\n",
3734            "    x += 1;\n",
3735            "}", //
3736        );
3737        while !new_text.is_empty() {
3738            let max_len = cmp::min(new_text.len(), 10);
3739            let len = rng.gen_range(1..=max_len);
3740            let (chunk, suffix) = new_text.split_at(len);
3741            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3742            new_text = suffix;
3743            cx.background_executor.run_until_parked();
3744        }
3745        drop(chunks_tx);
3746        cx.background_executor.run_until_parked();
3747
3748        assert_eq!(
3749            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3750            indoc! {"
3751                fn main() {
3752                    let mut x = 0;
3753                    while x < 10 {
3754                        x += 1;
3755                    }
3756                }
3757            "}
3758        );
3759    }
3760
3761    #[gpui::test(iterations = 10)]
3762    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
3763        cx.update(LanguageModelRegistry::test);
3764        cx.set_global(cx.update(SettingsStore::test));
3765        cx.update(language_settings::init);
3766
3767        let text = indoc! {"
3768            func main() {
3769            \tx := 0
3770            \tfor i := 0; i < 10; i++ {
3771            \t\tx++
3772            \t}
3773            }
3774        "};
3775        let buffer = cx.new_model(|cx| Buffer::local(text, cx));
3776        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3777        let range = buffer.read_with(cx, |buffer, cx| {
3778            let snapshot = buffer.snapshot(cx);
3779            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
3780        });
3781        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3782        let codegen = cx.new_model(|cx| {
3783            CodegenAlternative::new(
3784                buffer.clone(),
3785                range.clone(),
3786                true,
3787                None,
3788                prompt_builder,
3789                cx,
3790            )
3791        });
3792
3793        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3794        let new_text = concat!(
3795            "func main() {\n",
3796            "\tx := 0\n",
3797            "\tfor x < 10 {\n",
3798            "\t\tx++\n",
3799            "\t}", //
3800        );
3801        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
3802        drop(chunks_tx);
3803        cx.background_executor.run_until_parked();
3804
3805        assert_eq!(
3806            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3807            indoc! {"
3808                func main() {
3809                \tx := 0
3810                \tfor x < 10 {
3811                \t\tx++
3812                \t}
3813                }
3814            "}
3815        );
3816    }
3817
3818    #[gpui::test]
3819    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
3820        cx.update(LanguageModelRegistry::test);
3821        cx.set_global(cx.update(SettingsStore::test));
3822        cx.update(language_settings::init);
3823
3824        let text = indoc! {"
3825            fn main() {
3826                let x = 0;
3827            }
3828        "};
3829        let buffer =
3830            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3831        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3832        let range = buffer.read_with(cx, |buffer, cx| {
3833            let snapshot = buffer.snapshot(cx);
3834            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
3835        });
3836        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3837        let codegen = cx.new_model(|cx| {
3838            CodegenAlternative::new(
3839                buffer.clone(),
3840                range.clone(),
3841                false,
3842                None,
3843                prompt_builder,
3844                cx,
3845            )
3846        });
3847
3848        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3849        chunks_tx
3850            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
3851            .unwrap();
3852        drop(chunks_tx);
3853        cx.run_until_parked();
3854
3855        // The codegen is inactive, so the buffer doesn't get modified.
3856        assert_eq!(
3857            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3858            text
3859        );
3860
3861        // Activating the codegen applies the changes.
3862        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
3863        assert_eq!(
3864            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3865            indoc! {"
3866                fn main() {
3867                    let mut x = 0;
3868                    x += 1;
3869                }
3870            "}
3871        );
3872
3873        // Deactivating the codegen undoes the changes.
3874        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
3875        cx.run_until_parked();
3876        assert_eq!(
3877            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3878            text
3879        );
3880    }
3881
3882    #[gpui::test]
3883    async fn test_strip_invalid_spans_from_codeblock() {
3884        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
3885        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
3886        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
3887        assert_chunks(
3888            "```html\n```js\nLorem ipsum dolor\n```\n```",
3889            "```js\nLorem ipsum dolor\n```",
3890        )
3891        .await;
3892        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
3893        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
3894        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
3895        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
3896
3897        async fn assert_chunks(text: &str, expected_text: &str) {
3898            for chunk_size in 1..=text.len() {
3899                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
3900                    .map(|chunk| chunk.unwrap())
3901                    .collect::<String>()
3902                    .await;
3903                assert_eq!(
3904                    actual_text, expected_text,
3905                    "failed to strip invalid spans, chunk size: {}",
3906                    chunk_size
3907                );
3908            }
3909        }
3910
3911        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
3912            stream::iter(
3913                text.chars()
3914                    .collect::<Vec<_>>()
3915                    .chunks(size)
3916                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
3917                    .collect::<Vec<_>>(),
3918            )
3919        }
3920    }
3921
3922    fn simulate_response_stream(
3923        codegen: Model<CodegenAlternative>,
3924        cx: &mut TestAppContext,
3925    ) -> mpsc::UnboundedSender<String> {
3926        let (chunks_tx, chunks_rx) = mpsc::unbounded();
3927        codegen.update(cx, |codegen, cx| {
3928            codegen.handle_stream(
3929                String::new(),
3930                String::new(),
3931                None,
3932                future::ready(Ok(LanguageModelTextStream {
3933                    message_id: None,
3934                    stream: chunks_rx.map(Ok).boxed(),
3935                })),
3936                cx,
3937            );
3938        });
3939        chunks_tx
3940    }
3941
3942    fn rust_lang() -> Language {
3943        Language::new(
3944            LanguageConfig {
3945                name: "Rust".into(),
3946                matcher: LanguageMatcher {
3947                    path_suffixes: vec!["rs".to_string()],
3948                    ..Default::default()
3949                },
3950                ..Default::default()
3951            },
3952            Some(tree_sitter_rust::LANGUAGE.into()),
3953        )
3954        .with_indents_query(
3955            r#"
3956            (call_expression) @indent
3957            (field_expression) @indent
3958            (_ "(" ")" @end) @indent
3959            (_ "{" "}" @end) @indent
3960            "#,
3961        )
3962        .unwrap()
3963    }
3964}