inline_assistant.rs

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