inline_assistant.rs

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