copilot_completion_provider.rs

   1use crate::{Completion, Copilot};
   2use anyhow::Result;
   3use gpui::{AppContext, EntityId, Model, ModelContext, Task};
   4use inline_completion::{Direction, InlineCompletion, InlineCompletionProvider};
   5use language::{
   6    language_settings::{all_language_settings, AllLanguageSettings},
   7    Buffer, OffsetRangeExt, ToOffset,
   8};
   9use settings::Settings;
  10use std::{path::Path, time::Duration};
  11
  12pub const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  13
  14pub struct CopilotCompletionProvider {
  15    cycled: bool,
  16    buffer_id: Option<EntityId>,
  17    completions: Vec<Completion>,
  18    active_completion_index: usize,
  19    file_extension: Option<String>,
  20    pending_refresh: Option<Task<Result<()>>>,
  21    pending_cycling_refresh: Option<Task<Result<()>>>,
  22    copilot: Model<Copilot>,
  23}
  24
  25impl CopilotCompletionProvider {
  26    pub fn new(copilot: Model<Copilot>) -> Self {
  27        Self {
  28            cycled: false,
  29            buffer_id: None,
  30            completions: Vec::new(),
  31            active_completion_index: 0,
  32            file_extension: None,
  33            pending_refresh: None,
  34            pending_cycling_refresh: None,
  35            copilot,
  36        }
  37    }
  38
  39    fn active_completion(&self) -> Option<&Completion> {
  40        self.completions.get(self.active_completion_index)
  41    }
  42
  43    fn push_completion(&mut self, new_completion: Completion) {
  44        for completion in &self.completions {
  45            if completion.text == new_completion.text && completion.range == new_completion.range {
  46                return;
  47            }
  48        }
  49        self.completions.push(new_completion);
  50    }
  51}
  52
  53impl InlineCompletionProvider for CopilotCompletionProvider {
  54    fn name() -> &'static str {
  55        "copilot"
  56    }
  57
  58    fn display_name() -> &'static str {
  59        "Copilot"
  60    }
  61
  62    fn show_completions_in_menu() -> bool {
  63        false
  64    }
  65
  66    fn show_completions_in_normal_mode() -> bool {
  67        false
  68    }
  69
  70    fn is_refreshing(&self) -> bool {
  71        self.pending_refresh.is_some()
  72    }
  73
  74    fn is_enabled(
  75        &self,
  76        buffer: &Model<Buffer>,
  77        cursor_position: language::Anchor,
  78        cx: &AppContext,
  79    ) -> bool {
  80        if !self.copilot.read(cx).status().is_authorized() {
  81            return false;
  82        }
  83
  84        let buffer = buffer.read(cx);
  85        let file = buffer.file();
  86        let language = buffer.language_at(cursor_position);
  87        let settings = all_language_settings(file, cx);
  88        settings.inline_completions_enabled(language.as_ref(), file.map(|f| f.path().as_ref()), cx)
  89    }
  90
  91    fn refresh(
  92        &mut self,
  93        buffer: Model<Buffer>,
  94        cursor_position: language::Anchor,
  95        debounce: bool,
  96        cx: &mut ModelContext<Self>,
  97    ) {
  98        let copilot = self.copilot.clone();
  99        self.pending_refresh = Some(cx.spawn(|this, mut cx| async move {
 100            if debounce {
 101                cx.background_executor()
 102                    .timer(COPILOT_DEBOUNCE_TIMEOUT)
 103                    .await;
 104            }
 105
 106            let completions = copilot
 107                .update(&mut cx, |copilot, cx| {
 108                    copilot.completions(&buffer, cursor_position, cx)
 109                })?
 110                .await?;
 111
 112            this.update(&mut cx, |this, cx| {
 113                if !completions.is_empty() {
 114                    this.cycled = false;
 115                    this.pending_refresh = None;
 116                    this.pending_cycling_refresh = None;
 117                    this.completions.clear();
 118                    this.active_completion_index = 0;
 119                    this.buffer_id = Some(buffer.entity_id());
 120                    this.file_extension = buffer.read(cx).file().and_then(|file| {
 121                        Some(
 122                            Path::new(file.file_name(cx))
 123                                .extension()?
 124                                .to_str()?
 125                                .to_string(),
 126                        )
 127                    });
 128
 129                    for completion in completions {
 130                        this.push_completion(completion);
 131                    }
 132                    cx.notify();
 133                }
 134            })?;
 135
 136            Ok(())
 137        }));
 138    }
 139
 140    fn cycle(
 141        &mut self,
 142        buffer: Model<Buffer>,
 143        cursor_position: language::Anchor,
 144        direction: Direction,
 145        cx: &mut ModelContext<Self>,
 146    ) {
 147        if self.cycled {
 148            match direction {
 149                Direction::Prev => {
 150                    self.active_completion_index = if self.active_completion_index == 0 {
 151                        self.completions.len().saturating_sub(1)
 152                    } else {
 153                        self.active_completion_index - 1
 154                    };
 155                }
 156                Direction::Next => {
 157                    if self.completions.is_empty() {
 158                        self.active_completion_index = 0
 159                    } else {
 160                        self.active_completion_index =
 161                            (self.active_completion_index + 1) % self.completions.len();
 162                    }
 163                }
 164            }
 165
 166            cx.notify();
 167        } else {
 168            let copilot = self.copilot.clone();
 169            self.pending_cycling_refresh = Some(cx.spawn(|this, mut cx| async move {
 170                let completions = copilot
 171                    .update(&mut cx, |copilot, cx| {
 172                        copilot.completions_cycling(&buffer, cursor_position, cx)
 173                    })?
 174                    .await?;
 175
 176                this.update(&mut cx, |this, cx| {
 177                    this.cycled = true;
 178                    this.file_extension = buffer.read(cx).file().and_then(|file| {
 179                        Some(
 180                            Path::new(file.file_name(cx))
 181                                .extension()?
 182                                .to_str()?
 183                                .to_string(),
 184                        )
 185                    });
 186                    for completion in completions {
 187                        this.push_completion(completion);
 188                    }
 189                    this.cycle(buffer, cursor_position, direction, cx);
 190                })?;
 191
 192                Ok(())
 193            }));
 194        }
 195    }
 196
 197    fn accept(&mut self, cx: &mut ModelContext<Self>) {
 198        if let Some(completion) = self.active_completion() {
 199            self.copilot
 200                .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
 201                .detach_and_log_err(cx);
 202        }
 203    }
 204
 205    fn discard(&mut self, cx: &mut ModelContext<Self>) {
 206        let settings = AllLanguageSettings::get_global(cx);
 207
 208        let copilot_enabled = settings.inline_completions_enabled(None, None, cx);
 209
 210        if !copilot_enabled {
 211            return;
 212        }
 213
 214        self.copilot
 215            .update(cx, |copilot, cx| {
 216                copilot.discard_completions(&self.completions, cx)
 217            })
 218            .detach_and_log_err(cx);
 219    }
 220
 221    fn suggest(
 222        &mut self,
 223        buffer: &Model<Buffer>,
 224        cursor_position: language::Anchor,
 225        cx: &mut ModelContext<Self>,
 226    ) -> Option<InlineCompletion> {
 227        let buffer_id = buffer.entity_id();
 228        let buffer = buffer.read(cx);
 229        let completion = self.active_completion()?;
 230        if Some(buffer_id) != self.buffer_id
 231            || !completion.range.start.is_valid(buffer)
 232            || !completion.range.end.is_valid(buffer)
 233        {
 234            return None;
 235        }
 236
 237        let mut completion_range = completion.range.to_offset(buffer);
 238        let prefix_len = common_prefix(
 239            buffer.chars_for_range(completion_range.clone()),
 240            completion.text.chars(),
 241        );
 242        completion_range.start += prefix_len;
 243        let suffix_len = common_prefix(
 244            buffer.reversed_chars_for_range(completion_range.clone()),
 245            completion.text[prefix_len..].chars().rev(),
 246        );
 247        completion_range.end = completion_range.end.saturating_sub(suffix_len);
 248
 249        if completion_range.is_empty()
 250            && completion_range.start == cursor_position.to_offset(buffer)
 251        {
 252            let completion_text = &completion.text[prefix_len..completion.text.len() - suffix_len];
 253            if completion_text.trim().is_empty() {
 254                None
 255            } else {
 256                let position = cursor_position.bias_right(buffer);
 257                Some(InlineCompletion {
 258                    edits: vec![(position..position, completion_text.into())],
 259                })
 260            }
 261        } else {
 262            None
 263        }
 264    }
 265}
 266
 267fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
 268    a.zip(b)
 269        .take_while(|(a, b)| a == b)
 270        .map(|(a, _)| a.len_utf8())
 271        .sum()
 272}
 273
 274#[cfg(test)]
 275mod tests {
 276    use super::*;
 277    use editor::{
 278        test::editor_lsp_test_context::EditorLspTestContext, Editor, ExcerptRange, MultiBuffer,
 279    };
 280    use fs::FakeFs;
 281    use futures::StreamExt;
 282    use gpui::{BackgroundExecutor, Context, TestAppContext, UpdateGlobal};
 283    use indoc::indoc;
 284    use language::{
 285        language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
 286        Point,
 287    };
 288    use project::Project;
 289    use serde_json::json;
 290    use settings::SettingsStore;
 291    use std::future::Future;
 292    use util::test::{marked_text_ranges_by, TextRangeMarker};
 293
 294    #[gpui::test(iterations = 10)]
 295    async fn test_copilot(executor: BackgroundExecutor, cx: &mut TestAppContext) {
 296        // flaky
 297        init_test(cx, |_| {});
 298
 299        let (copilot, copilot_lsp) = Copilot::fake(cx);
 300        let mut cx = EditorLspTestContext::new_rust(
 301            lsp::ServerCapabilities {
 302                completion_provider: Some(lsp::CompletionOptions {
 303                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
 304                    ..Default::default()
 305                }),
 306                ..Default::default()
 307            },
 308            cx,
 309        )
 310        .await;
 311        let copilot_provider = cx.new_model(|_| CopilotCompletionProvider::new(copilot));
 312        cx.update_editor(|editor, cx| {
 313            editor.set_inline_completion_provider(Some(copilot_provider), cx)
 314        });
 315
 316        cx.set_state(indoc! {"
 317            oneˇ
 318            two
 319            three
 320        "});
 321        cx.simulate_keystroke(".");
 322        drop(handle_completion_request(
 323            &mut cx,
 324            indoc! {"
 325                one.|<>
 326                two
 327                three
 328            "},
 329            vec!["completion_a", "completion_b"],
 330        ));
 331        handle_copilot_completion_request(
 332            &copilot_lsp,
 333            vec![crate::request::Completion {
 334                text: "one.copilot1".into(),
 335                range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
 336                ..Default::default()
 337            }],
 338            vec![],
 339        );
 340        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 341        cx.update_editor(|editor, cx| {
 342            assert!(editor.context_menu_visible());
 343            assert!(!editor.context_menu_contains_inline_completion());
 344            assert!(!editor.has_active_inline_completion());
 345            // Since we have both, the copilot suggestion is not shown inline
 346            assert_eq!(editor.text(cx), "one.\ntwo\nthree\n");
 347            assert_eq!(editor.display_text(cx), "one.\ntwo\nthree\n");
 348
 349            // Confirming a non-copilot completion inserts it and hides the context menu, without showing
 350            // the copilot suggestion afterwards.
 351            editor
 352                .confirm_completion(&Default::default(), cx)
 353                .unwrap()
 354                .detach();
 355            assert!(!editor.context_menu_visible());
 356            assert!(!editor.has_active_inline_completion());
 357            assert_eq!(editor.text(cx), "one.completion_a\ntwo\nthree\n");
 358            assert_eq!(editor.display_text(cx), "one.completion_a\ntwo\nthree\n");
 359        });
 360
 361        // Reset editor and only return copilot suggestions
 362        cx.set_state(indoc! {"
 363            oneˇ
 364            two
 365            three
 366        "});
 367        cx.simulate_keystroke(".");
 368
 369        drop(handle_completion_request(
 370            &mut cx,
 371            indoc! {"
 372                one.|<>
 373                two
 374                three
 375            "},
 376            vec![],
 377        ));
 378        handle_copilot_completion_request(
 379            &copilot_lsp,
 380            vec![crate::request::Completion {
 381                text: "one.copilot1".into(),
 382                range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
 383                ..Default::default()
 384            }],
 385            vec![],
 386        );
 387        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 388        cx.update_editor(|editor, cx| {
 389            assert!(!editor.context_menu_visible());
 390            assert!(editor.has_active_inline_completion());
 391            // Since only the copilot is available, it's shown inline
 392            assert_eq!(editor.display_text(cx), "one.copilot1\ntwo\nthree\n");
 393            assert_eq!(editor.text(cx), "one.\ntwo\nthree\n");
 394        });
 395
 396        // Ensure existing inline completion is interpolated when inserting again.
 397        cx.simulate_keystroke("c");
 398        executor.run_until_parked();
 399        cx.update_editor(|editor, cx| {
 400            assert!(!editor.context_menu_visible());
 401            assert!(!editor.context_menu_contains_inline_completion());
 402            assert!(editor.has_active_inline_completion());
 403            assert_eq!(editor.display_text(cx), "one.copilot1\ntwo\nthree\n");
 404            assert_eq!(editor.text(cx), "one.c\ntwo\nthree\n");
 405        });
 406
 407        // After debouncing, new Copilot completions should be requested.
 408        handle_copilot_completion_request(
 409            &copilot_lsp,
 410            vec![crate::request::Completion {
 411                text: "one.copilot2".into(),
 412                range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 5)),
 413                ..Default::default()
 414            }],
 415            vec![],
 416        );
 417        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 418        cx.update_editor(|editor, cx| {
 419            assert!(!editor.context_menu_visible());
 420            assert!(editor.has_active_inline_completion());
 421            assert!(!editor.context_menu_contains_inline_completion());
 422            assert_eq!(editor.display_text(cx), "one.copilot2\ntwo\nthree\n");
 423            assert_eq!(editor.text(cx), "one.c\ntwo\nthree\n");
 424
 425            // Canceling should remove the active Copilot suggestion.
 426            editor.cancel(&Default::default(), cx);
 427            assert!(!editor.has_active_inline_completion());
 428            assert_eq!(editor.display_text(cx), "one.c\ntwo\nthree\n");
 429            assert_eq!(editor.text(cx), "one.c\ntwo\nthree\n");
 430
 431            // After canceling, tabbing shouldn't insert the previously shown suggestion.
 432            editor.tab(&Default::default(), cx);
 433            assert!(!editor.has_active_inline_completion());
 434            assert_eq!(editor.display_text(cx), "one.c   \ntwo\nthree\n");
 435            assert_eq!(editor.text(cx), "one.c   \ntwo\nthree\n");
 436
 437            // When undoing the previously active suggestion is shown again.
 438            editor.undo(&Default::default(), cx);
 439            assert!(editor.has_active_inline_completion());
 440            assert_eq!(editor.display_text(cx), "one.copilot2\ntwo\nthree\n");
 441            assert_eq!(editor.text(cx), "one.c\ntwo\nthree\n");
 442        });
 443
 444        // If an edit occurs outside of this editor, the suggestion is still correctly interpolated.
 445        cx.update_buffer(|buffer, cx| buffer.edit([(5..5, "o")], None, cx));
 446        cx.update_editor(|editor, cx| {
 447            assert!(editor.has_active_inline_completion());
 448            assert_eq!(editor.display_text(cx), "one.copilot2\ntwo\nthree\n");
 449            assert_eq!(editor.text(cx), "one.co\ntwo\nthree\n");
 450
 451            // AcceptInlineCompletion when there is an active suggestion inserts it.
 452            editor.accept_inline_completion(&Default::default(), cx);
 453            assert!(!editor.has_active_inline_completion());
 454            assert_eq!(editor.display_text(cx), "one.copilot2\ntwo\nthree\n");
 455            assert_eq!(editor.text(cx), "one.copilot2\ntwo\nthree\n");
 456
 457            // When undoing the previously active suggestion is shown again.
 458            editor.undo(&Default::default(), cx);
 459            assert!(editor.has_active_inline_completion());
 460            assert_eq!(editor.display_text(cx), "one.copilot2\ntwo\nthree\n");
 461            assert_eq!(editor.text(cx), "one.co\ntwo\nthree\n");
 462
 463            // Hide suggestion.
 464            editor.cancel(&Default::default(), cx);
 465            assert!(!editor.has_active_inline_completion());
 466            assert_eq!(editor.display_text(cx), "one.co\ntwo\nthree\n");
 467            assert_eq!(editor.text(cx), "one.co\ntwo\nthree\n");
 468        });
 469
 470        // If an edit occurs outside of this editor but no suggestion is being shown,
 471        // we won't make it visible.
 472        cx.update_buffer(|buffer, cx| buffer.edit([(6..6, "p")], None, cx));
 473        cx.update_editor(|editor, cx| {
 474            assert!(!editor.has_active_inline_completion());
 475            assert_eq!(editor.display_text(cx), "one.cop\ntwo\nthree\n");
 476            assert_eq!(editor.text(cx), "one.cop\ntwo\nthree\n");
 477        });
 478
 479        // Reset the editor to verify how suggestions behave when tabbing on leading indentation.
 480        cx.update_editor(|editor, cx| {
 481            editor.set_text("fn foo() {\n  \n}", cx);
 482            editor.change_selections(None, cx, |s| {
 483                s.select_ranges([Point::new(1, 2)..Point::new(1, 2)])
 484            });
 485        });
 486        handle_copilot_completion_request(
 487            &copilot_lsp,
 488            vec![crate::request::Completion {
 489                text: "    let x = 4;".into(),
 490                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 2)),
 491                ..Default::default()
 492            }],
 493            vec![],
 494        );
 495
 496        cx.update_editor(|editor, cx| editor.next_inline_completion(&Default::default(), cx));
 497        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 498        cx.update_editor(|editor, cx| {
 499            assert!(editor.has_active_inline_completion());
 500            assert_eq!(editor.display_text(cx), "fn foo() {\n    let x = 4;\n}");
 501            assert_eq!(editor.text(cx), "fn foo() {\n  \n}");
 502
 503            // Tabbing inside of leading whitespace inserts indentation without accepting the suggestion.
 504            editor.tab(&Default::default(), cx);
 505            assert!(editor.has_active_inline_completion());
 506            assert_eq!(editor.text(cx), "fn foo() {\n    \n}");
 507            assert_eq!(editor.display_text(cx), "fn foo() {\n    let x = 4;\n}");
 508
 509            // Using AcceptInlineCompletion again accepts the suggestion.
 510            editor.accept_inline_completion(&Default::default(), cx);
 511            assert!(!editor.has_active_inline_completion());
 512            assert_eq!(editor.text(cx), "fn foo() {\n    let x = 4;\n}");
 513            assert_eq!(editor.display_text(cx), "fn foo() {\n    let x = 4;\n}");
 514        });
 515    }
 516
 517    #[gpui::test(iterations = 10)]
 518    async fn test_accept_partial_copilot_suggestion(
 519        executor: BackgroundExecutor,
 520        cx: &mut TestAppContext,
 521    ) {
 522        // flaky
 523        init_test(cx, |_| {});
 524
 525        let (copilot, copilot_lsp) = Copilot::fake(cx);
 526        let mut cx = EditorLspTestContext::new_rust(
 527            lsp::ServerCapabilities {
 528                completion_provider: Some(lsp::CompletionOptions {
 529                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
 530                    ..Default::default()
 531                }),
 532                ..Default::default()
 533            },
 534            cx,
 535        )
 536        .await;
 537        let copilot_provider = cx.new_model(|_| CopilotCompletionProvider::new(copilot));
 538        cx.update_editor(|editor, cx| {
 539            editor.set_inline_completion_provider(Some(copilot_provider), cx)
 540        });
 541
 542        // Setup the editor with a completion request.
 543        cx.set_state(indoc! {"
 544            oneˇ
 545            two
 546            three
 547        "});
 548        cx.simulate_keystroke(".");
 549        drop(handle_completion_request(
 550            &mut cx,
 551            indoc! {"
 552                one.|<>
 553                two
 554                three
 555            "},
 556            vec![],
 557        ));
 558        handle_copilot_completion_request(
 559            &copilot_lsp,
 560            vec![crate::request::Completion {
 561                text: "one.copilot1".into(),
 562                range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
 563                ..Default::default()
 564            }],
 565            vec![],
 566        );
 567        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 568        cx.update_editor(|editor, cx| {
 569            assert!(editor.has_active_inline_completion());
 570
 571            // Accepting the first word of the suggestion should only accept the first word and still show the rest.
 572            editor.accept_partial_inline_completion(&Default::default(), cx);
 573            assert!(editor.has_active_inline_completion());
 574            assert_eq!(editor.text(cx), "one.copilot\ntwo\nthree\n");
 575            assert_eq!(editor.display_text(cx), "one.copilot1\ntwo\nthree\n");
 576
 577            // Accepting next word should accept the non-word and copilot suggestion should be gone
 578            editor.accept_partial_inline_completion(&Default::default(), cx);
 579            assert!(!editor.has_active_inline_completion());
 580            assert_eq!(editor.text(cx), "one.copilot1\ntwo\nthree\n");
 581            assert_eq!(editor.display_text(cx), "one.copilot1\ntwo\nthree\n");
 582        });
 583
 584        // Reset the editor and check non-word and whitespace completion
 585        cx.set_state(indoc! {"
 586            oneˇ
 587            two
 588            three
 589        "});
 590        cx.simulate_keystroke(".");
 591        drop(handle_completion_request(
 592            &mut cx,
 593            indoc! {"
 594                one.|<>
 595                two
 596                three
 597            "},
 598            vec![],
 599        ));
 600        handle_copilot_completion_request(
 601            &copilot_lsp,
 602            vec![crate::request::Completion {
 603                text: "one.123. copilot\n 456".into(),
 604                range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 4)),
 605                ..Default::default()
 606            }],
 607            vec![],
 608        );
 609        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 610        cx.update_editor(|editor, cx| {
 611            assert!(editor.has_active_inline_completion());
 612
 613            // Accepting the first word (non-word) of the suggestion should only accept the first word and still show the rest.
 614            editor.accept_partial_inline_completion(&Default::default(), cx);
 615            assert!(editor.has_active_inline_completion());
 616            assert_eq!(editor.text(cx), "one.123. \ntwo\nthree\n");
 617            assert_eq!(
 618                editor.display_text(cx),
 619                "one.123. copilot\n 456\ntwo\nthree\n"
 620            );
 621
 622            // Accepting next word should accept the next word and copilot suggestion should still exist
 623            editor.accept_partial_inline_completion(&Default::default(), cx);
 624            assert!(editor.has_active_inline_completion());
 625            assert_eq!(editor.text(cx), "one.123. copilot\ntwo\nthree\n");
 626            assert_eq!(
 627                editor.display_text(cx),
 628                "one.123. copilot\n 456\ntwo\nthree\n"
 629            );
 630
 631            // Accepting the whitespace should accept the non-word/whitespaces with newline and copilot suggestion should be gone
 632            editor.accept_partial_inline_completion(&Default::default(), cx);
 633            assert!(!editor.has_active_inline_completion());
 634            assert_eq!(editor.text(cx), "one.123. copilot\n 456\ntwo\nthree\n");
 635            assert_eq!(
 636                editor.display_text(cx),
 637                "one.123. copilot\n 456\ntwo\nthree\n"
 638            );
 639        });
 640    }
 641
 642    #[gpui::test]
 643    async fn test_copilot_completion_invalidation(
 644        executor: BackgroundExecutor,
 645        cx: &mut TestAppContext,
 646    ) {
 647        init_test(cx, |_| {});
 648
 649        let (copilot, copilot_lsp) = Copilot::fake(cx);
 650        let mut cx = EditorLspTestContext::new_rust(
 651            lsp::ServerCapabilities {
 652                completion_provider: Some(lsp::CompletionOptions {
 653                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
 654                    ..Default::default()
 655                }),
 656                ..Default::default()
 657            },
 658            cx,
 659        )
 660        .await;
 661        let copilot_provider = cx.new_model(|_| CopilotCompletionProvider::new(copilot));
 662        cx.update_editor(|editor, cx| {
 663            editor.set_inline_completion_provider(Some(copilot_provider), cx)
 664        });
 665
 666        cx.set_state(indoc! {"
 667            one
 668            twˇ
 669            three
 670        "});
 671
 672        handle_copilot_completion_request(
 673            &copilot_lsp,
 674            vec![crate::request::Completion {
 675                text: "two.foo()".into(),
 676                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 2)),
 677                ..Default::default()
 678            }],
 679            vec![],
 680        );
 681        cx.update_editor(|editor, cx| editor.next_inline_completion(&Default::default(), cx));
 682        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 683        cx.update_editor(|editor, cx| {
 684            assert!(editor.has_active_inline_completion());
 685            assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
 686            assert_eq!(editor.text(cx), "one\ntw\nthree\n");
 687
 688            editor.backspace(&Default::default(), cx);
 689            assert!(editor.has_active_inline_completion());
 690            assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
 691            assert_eq!(editor.text(cx), "one\nt\nthree\n");
 692
 693            editor.backspace(&Default::default(), cx);
 694            assert!(editor.has_active_inline_completion());
 695            assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
 696            assert_eq!(editor.text(cx), "one\n\nthree\n");
 697
 698            // Deleting across the original suggestion range invalidates it.
 699            editor.backspace(&Default::default(), cx);
 700            assert!(!editor.has_active_inline_completion());
 701            assert_eq!(editor.display_text(cx), "one\nthree\n");
 702            assert_eq!(editor.text(cx), "one\nthree\n");
 703
 704            // Undoing the deletion restores the suggestion.
 705            editor.undo(&Default::default(), cx);
 706            assert!(editor.has_active_inline_completion());
 707            assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
 708            assert_eq!(editor.text(cx), "one\n\nthree\n");
 709        });
 710    }
 711
 712    #[gpui::test]
 713    async fn test_copilot_multibuffer(executor: BackgroundExecutor, cx: &mut TestAppContext) {
 714        init_test(cx, |_| {});
 715
 716        let (copilot, copilot_lsp) = Copilot::fake(cx);
 717
 718        let buffer_1 = cx.new_model(|cx| Buffer::local("a = 1\nb = 2\n", cx));
 719        let buffer_2 = cx.new_model(|cx| Buffer::local("c = 3\nd = 4\n", cx));
 720        let multibuffer = cx.new_model(|cx| {
 721            let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
 722            multibuffer.push_excerpts(
 723                buffer_1.clone(),
 724                [ExcerptRange {
 725                    context: Point::new(0, 0)..Point::new(2, 0),
 726                    primary: None,
 727                }],
 728                cx,
 729            );
 730            multibuffer.push_excerpts(
 731                buffer_2.clone(),
 732                [ExcerptRange {
 733                    context: Point::new(0, 0)..Point::new(2, 0),
 734                    primary: None,
 735                }],
 736                cx,
 737            );
 738            multibuffer
 739        });
 740        let editor = cx.add_window(|cx| Editor::for_multibuffer(multibuffer, None, true, cx));
 741        editor.update(cx, |editor, cx| editor.focus(cx)).unwrap();
 742        let copilot_provider = cx.new_model(|_| CopilotCompletionProvider::new(copilot));
 743        editor
 744            .update(cx, |editor, cx| {
 745                editor.set_inline_completion_provider(Some(copilot_provider), cx)
 746            })
 747            .unwrap();
 748
 749        handle_copilot_completion_request(
 750            &copilot_lsp,
 751            vec![crate::request::Completion {
 752                text: "b = 2 + a".into(),
 753                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 5)),
 754                ..Default::default()
 755            }],
 756            vec![],
 757        );
 758        _ = editor.update(cx, |editor, cx| {
 759            // Ensure copilot suggestions are shown for the first excerpt.
 760            editor.change_selections(None, cx, |s| {
 761                s.select_ranges([Point::new(1, 5)..Point::new(1, 5)])
 762            });
 763            editor.next_inline_completion(&Default::default(), cx);
 764        });
 765        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 766        _ = editor.update(cx, |editor, cx| {
 767            assert!(editor.has_active_inline_completion());
 768            assert_eq!(
 769                editor.display_text(cx),
 770                "\n\n\na = 1\nb = 2 + a\n\n\n\n\n\nc = 3\nd = 4\n\n"
 771            );
 772            assert_eq!(editor.text(cx), "a = 1\nb = 2\n\nc = 3\nd = 4\n");
 773        });
 774
 775        handle_copilot_completion_request(
 776            &copilot_lsp,
 777            vec![crate::request::Completion {
 778                text: "d = 4 + c".into(),
 779                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 6)),
 780                ..Default::default()
 781            }],
 782            vec![],
 783        );
 784        _ = editor.update(cx, |editor, cx| {
 785            // Move to another excerpt, ensuring the suggestion gets cleared.
 786            editor.change_selections(None, cx, |s| {
 787                s.select_ranges([Point::new(4, 5)..Point::new(4, 5)])
 788            });
 789            assert!(!editor.has_active_inline_completion());
 790            assert_eq!(
 791                editor.display_text(cx),
 792                "\n\n\na = 1\nb = 2\n\n\n\n\n\nc = 3\nd = 4\n\n"
 793            );
 794            assert_eq!(editor.text(cx), "a = 1\nb = 2\n\nc = 3\nd = 4\n");
 795
 796            // Type a character, ensuring we don't even try to interpolate the previous suggestion.
 797            editor.handle_input(" ", cx);
 798            assert!(!editor.has_active_inline_completion());
 799            assert_eq!(
 800                editor.display_text(cx),
 801                "\n\n\na = 1\nb = 2\n\n\n\n\n\nc = 3\nd = 4 \n\n"
 802            );
 803            assert_eq!(editor.text(cx), "a = 1\nb = 2\n\nc = 3\nd = 4 \n");
 804        });
 805
 806        // Ensure the new suggestion is displayed when the debounce timeout expires.
 807        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 808        _ = editor.update(cx, |editor, cx| {
 809            assert!(editor.has_active_inline_completion());
 810            assert_eq!(
 811                editor.display_text(cx),
 812                "\n\n\na = 1\nb = 2\n\n\n\n\n\nc = 3\nd = 4 + c\n\n"
 813            );
 814            assert_eq!(editor.text(cx), "a = 1\nb = 2\n\nc = 3\nd = 4 \n");
 815        });
 816    }
 817
 818    #[gpui::test]
 819    async fn test_copilot_does_not_prevent_completion_triggers(
 820        executor: BackgroundExecutor,
 821        cx: &mut TestAppContext,
 822    ) {
 823        init_test(cx, |_| {});
 824
 825        let (copilot, copilot_lsp) = Copilot::fake(cx);
 826        let mut cx = EditorLspTestContext::new_rust(
 827            lsp::ServerCapabilities {
 828                completion_provider: Some(lsp::CompletionOptions {
 829                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
 830                    ..lsp::CompletionOptions::default()
 831                }),
 832                ..lsp::ServerCapabilities::default()
 833            },
 834            cx,
 835        )
 836        .await;
 837        let copilot_provider = cx.new_model(|_| CopilotCompletionProvider::new(copilot));
 838        cx.update_editor(|editor, cx| {
 839            editor.set_inline_completion_provider(Some(copilot_provider), cx)
 840        });
 841
 842        cx.set_state(indoc! {"
 843                one
 844                twˇ
 845                three
 846            "});
 847
 848        drop(handle_completion_request(
 849            &mut cx,
 850            indoc! {"
 851                one
 852                tw|<>
 853                three
 854            "},
 855            vec!["completion_a", "completion_b"],
 856        ));
 857        handle_copilot_completion_request(
 858            &copilot_lsp,
 859            vec![crate::request::Completion {
 860                text: "two.foo()".into(),
 861                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 2)),
 862                ..Default::default()
 863            }],
 864            vec![],
 865        );
 866        cx.update_editor(|editor, cx| editor.next_inline_completion(&Default::default(), cx));
 867        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 868        cx.update_editor(|editor, cx| {
 869            assert!(!editor.context_menu_visible());
 870            assert!(editor.has_active_inline_completion());
 871            assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
 872            assert_eq!(editor.text(cx), "one\ntw\nthree\n");
 873        });
 874
 875        cx.simulate_keystroke("o");
 876        drop(handle_completion_request(
 877            &mut cx,
 878            indoc! {"
 879                one
 880                two|<>
 881                three
 882            "},
 883            vec!["completion_a_2", "completion_b_2"],
 884        ));
 885        handle_copilot_completion_request(
 886            &copilot_lsp,
 887            vec![crate::request::Completion {
 888                text: "two.foo()".into(),
 889                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 3)),
 890                ..Default::default()
 891            }],
 892            vec![],
 893        );
 894        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 895        cx.update_editor(|editor, cx| {
 896            assert!(!editor.context_menu_visible());
 897            assert!(editor.has_active_inline_completion());
 898            assert_eq!(editor.display_text(cx), "one\ntwo.foo()\nthree\n");
 899            assert_eq!(editor.text(cx), "one\ntwo\nthree\n");
 900        });
 901
 902        cx.simulate_keystroke(".");
 903        drop(handle_completion_request(
 904            &mut cx,
 905            indoc! {"
 906                one
 907                two.|<>
 908                three
 909            "},
 910            vec!["something_else()"],
 911        ));
 912        handle_copilot_completion_request(
 913            &copilot_lsp,
 914            vec![crate::request::Completion {
 915                text: "two.foo()".into(),
 916                range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 4)),
 917                ..Default::default()
 918            }],
 919            vec![],
 920        );
 921        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
 922        cx.update_editor(|editor, cx| {
 923            assert!(editor.context_menu_visible());
 924            assert!(!editor.context_menu_contains_inline_completion());
 925            assert!(!editor.has_active_inline_completion(),);
 926            assert_eq!(editor.text(cx), "one\ntwo.\nthree\n");
 927        });
 928    }
 929
 930    #[gpui::test]
 931    async fn test_copilot_disabled_globs(executor: BackgroundExecutor, cx: &mut TestAppContext) {
 932        init_test(cx, |settings| {
 933            settings
 934                .inline_completions
 935                .get_or_insert(Default::default())
 936                .disabled_globs = Some(vec![".env*".to_string()]);
 937        });
 938
 939        let (copilot, copilot_lsp) = Copilot::fake(cx);
 940
 941        let fs = FakeFs::new(cx.executor());
 942        fs.insert_tree(
 943            "/test",
 944            json!({
 945                ".env": "SECRET=something\n",
 946                "README.md": "hello\nworld\nhow\nare\nyou\ntoday"
 947            }),
 948        )
 949        .await;
 950        let project = Project::test(fs, ["/test".as_ref()], cx).await;
 951
 952        let private_buffer = project
 953            .update(cx, |project, cx| {
 954                project.open_local_buffer("/test/.env", cx)
 955            })
 956            .await
 957            .unwrap();
 958        let public_buffer = project
 959            .update(cx, |project, cx| {
 960                project.open_local_buffer("/test/README.md", cx)
 961            })
 962            .await
 963            .unwrap();
 964
 965        let multibuffer = cx.new_model(|cx| {
 966            let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
 967            multibuffer.push_excerpts(
 968                private_buffer.clone(),
 969                [ExcerptRange {
 970                    context: Point::new(0, 0)..Point::new(1, 0),
 971                    primary: None,
 972                }],
 973                cx,
 974            );
 975            multibuffer.push_excerpts(
 976                public_buffer.clone(),
 977                [ExcerptRange {
 978                    context: Point::new(0, 0)..Point::new(6, 0),
 979                    primary: None,
 980                }],
 981                cx,
 982            );
 983            multibuffer
 984        });
 985        let editor = cx.add_window(|cx| Editor::for_multibuffer(multibuffer, None, true, cx));
 986        editor.update(cx, |editor, cx| editor.focus(cx)).unwrap();
 987        let copilot_provider = cx.new_model(|_| CopilotCompletionProvider::new(copilot));
 988        editor
 989            .update(cx, |editor, cx| {
 990                editor.set_inline_completion_provider(Some(copilot_provider), cx)
 991            })
 992            .unwrap();
 993
 994        let mut copilot_requests = copilot_lsp
 995            .handle_request::<crate::request::GetCompletions, _, _>(
 996                move |_params, _cx| async move {
 997                    Ok(crate::request::GetCompletionsResult {
 998                        completions: vec![crate::request::Completion {
 999                            text: "next line".into(),
1000                            range: lsp::Range::new(
1001                                lsp::Position::new(1, 0),
1002                                lsp::Position::new(1, 0),
1003                            ),
1004                            ..Default::default()
1005                        }],
1006                    })
1007                },
1008            );
1009
1010        _ = editor.update(cx, |editor, cx| {
1011            editor.change_selections(None, cx, |selections| {
1012                selections.select_ranges([Point::new(0, 0)..Point::new(0, 0)])
1013            });
1014            editor.refresh_inline_completion(true, false, cx);
1015        });
1016
1017        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
1018        assert!(copilot_requests.try_next().is_err());
1019
1020        _ = editor.update(cx, |editor, cx| {
1021            editor.change_selections(None, cx, |s| {
1022                s.select_ranges([Point::new(5, 0)..Point::new(5, 0)])
1023            });
1024            editor.refresh_inline_completion(true, false, cx);
1025        });
1026
1027        executor.advance_clock(COPILOT_DEBOUNCE_TIMEOUT);
1028        assert!(copilot_requests.try_next().is_ok());
1029    }
1030
1031    fn handle_copilot_completion_request(
1032        lsp: &lsp::FakeLanguageServer,
1033        completions: Vec<crate::request::Completion>,
1034        completions_cycling: Vec<crate::request::Completion>,
1035    ) {
1036        lsp.handle_request::<crate::request::GetCompletions, _, _>(move |_params, _cx| {
1037            let completions = completions.clone();
1038            async move {
1039                Ok(crate::request::GetCompletionsResult {
1040                    completions: completions.clone(),
1041                })
1042            }
1043        });
1044        lsp.handle_request::<crate::request::GetCompletionsCycling, _, _>(move |_params, _cx| {
1045            let completions_cycling = completions_cycling.clone();
1046            async move {
1047                Ok(crate::request::GetCompletionsResult {
1048                    completions: completions_cycling.clone(),
1049                })
1050            }
1051        });
1052    }
1053
1054    fn handle_completion_request(
1055        cx: &mut EditorLspTestContext,
1056        marked_string: &str,
1057        completions: Vec<&'static str>,
1058    ) -> impl Future<Output = ()> {
1059        let complete_from_marker: TextRangeMarker = '|'.into();
1060        let replace_range_marker: TextRangeMarker = ('<', '>').into();
1061        let (_, mut marked_ranges) = marked_text_ranges_by(
1062            marked_string,
1063            vec![complete_from_marker.clone(), replace_range_marker.clone()],
1064        );
1065
1066        let complete_from_position =
1067            cx.to_lsp(marked_ranges.remove(&complete_from_marker).unwrap()[0].start);
1068        let replace_range =
1069            cx.to_lsp_range(marked_ranges.remove(&replace_range_marker).unwrap()[0].clone());
1070
1071        let mut request =
1072            cx.handle_request::<lsp::request::Completion, _, _>(move |url, params, _| {
1073                let completions = completions.clone();
1074                async move {
1075                    assert_eq!(params.text_document_position.text_document.uri, url.clone());
1076                    assert_eq!(
1077                        params.text_document_position.position,
1078                        complete_from_position
1079                    );
1080                    Ok(Some(lsp::CompletionResponse::Array(
1081                        completions
1082                            .iter()
1083                            .map(|completion_text| lsp::CompletionItem {
1084                                label: completion_text.to_string(),
1085                                text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1086                                    range: replace_range,
1087                                    new_text: completion_text.to_string(),
1088                                })),
1089                                ..Default::default()
1090                            })
1091                            .collect(),
1092                    )))
1093                }
1094            });
1095
1096        async move {
1097            request.next().await;
1098        }
1099    }
1100
1101    fn init_test(cx: &mut TestAppContext, f: fn(&mut AllLanguageSettingsContent)) {
1102        cx.update(|cx| {
1103            let store = SettingsStore::test(cx);
1104            cx.set_global(store);
1105            theme::init(theme::LoadThemes::JustBase, cx);
1106            client::init_settings(cx);
1107            language::init(cx);
1108            editor::init_settings(cx);
1109            Project::init_settings(cx);
1110            workspace::init_settings(cx);
1111            SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| {
1112                store.update_user_settings::<AllLanguageSettings>(cx, f);
1113            });
1114        });
1115    }
1116}