inline_assistant.rs

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