inline_assistant.rs

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