inline_assistant.rs

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