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