codegen.rs

  1use crate::streaming_diff::{Hunk, StreamingDiff};
  2use ai::completion::{CompletionProvider, CompletionRequest};
  3use anyhow::Result;
  4use editor::{Anchor, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint};
  5use futures::{channel::mpsc, SinkExt, Stream, StreamExt};
  6use gpui::{EventEmitter, Model, ModelContext, Task};
  7use language::{Rope, TransactionId};
  8use multi_buffer;
  9use std::{cmp, future, ops::Range, sync::Arc};
 10
 11pub enum Event {
 12    Finished,
 13    Undone,
 14}
 15
 16#[derive(Clone)]
 17pub enum CodegenKind {
 18    Transform { range: Range<Anchor> },
 19    Generate { position: Anchor },
 20}
 21
 22pub struct Codegen {
 23    provider: Arc<dyn CompletionProvider>,
 24    buffer: Model<MultiBuffer>,
 25    snapshot: MultiBufferSnapshot,
 26    kind: CodegenKind,
 27    last_equal_ranges: Vec<Range<Anchor>>,
 28    transaction_id: Option<TransactionId>,
 29    error: Option<anyhow::Error>,
 30    generation: Task<()>,
 31    idle: bool,
 32    _subscription: gpui::Subscription,
 33}
 34
 35impl EventEmitter<Event> for Codegen {}
 36
 37impl Codegen {
 38    pub fn new(
 39        buffer: Model<MultiBuffer>,
 40        kind: CodegenKind,
 41        provider: Arc<dyn CompletionProvider>,
 42        cx: &mut ModelContext<Self>,
 43    ) -> Self {
 44        let snapshot = buffer.read(cx).snapshot(cx);
 45        Self {
 46            provider,
 47            buffer: buffer.clone(),
 48            snapshot,
 49            kind,
 50            last_equal_ranges: Default::default(),
 51            transaction_id: Default::default(),
 52            error: Default::default(),
 53            idle: true,
 54            generation: Task::ready(()),
 55            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
 56        }
 57    }
 58
 59    fn handle_buffer_event(
 60        &mut self,
 61        _buffer: Model<MultiBuffer>,
 62        event: &multi_buffer::Event,
 63        cx: &mut ModelContext<Self>,
 64    ) {
 65        if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
 66            if self.transaction_id == Some(*transaction_id) {
 67                self.transaction_id = None;
 68                self.generation = Task::ready(());
 69                cx.emit(Event::Undone);
 70            }
 71        }
 72    }
 73
 74    pub fn range(&self) -> Range<Anchor> {
 75        match &self.kind {
 76            CodegenKind::Transform { range } => range.clone(),
 77            CodegenKind::Generate { position } => position.bias_left(&self.snapshot)..*position,
 78        }
 79    }
 80
 81    pub fn kind(&self) -> &CodegenKind {
 82        &self.kind
 83    }
 84
 85    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
 86        &self.last_equal_ranges
 87    }
 88
 89    pub fn idle(&self) -> bool {
 90        self.idle
 91    }
 92
 93    pub fn error(&self) -> Option<&anyhow::Error> {
 94        self.error.as_ref()
 95    }
 96
 97    pub fn start(&mut self, prompt: Box<dyn CompletionRequest>, cx: &mut ModelContext<Self>) {
 98        let range = self.range();
 99        let snapshot = self.snapshot.clone();
100        let selected_text = snapshot
101            .text_for_range(range.start..range.end)
102            .collect::<Rope>();
103
104        let selection_start = range.start.to_point(&snapshot);
105        let suggested_line_indent = snapshot
106            .suggested_indents(selection_start.row..selection_start.row + 1, cx)
107            .into_values()
108            .next()
109            .unwrap_or_else(|| snapshot.indent_size_for_line(selection_start.row));
110
111        let response = self.provider.complete(prompt);
112        self.generation = cx.spawn(|this, mut cx| {
113            async move {
114                let generate = async {
115                    let mut edit_start = range.start.to_offset(&snapshot);
116
117                    let (mut hunks_tx, mut hunks_rx) = mpsc::channel(1);
118                    let diff = cx.background_executor().spawn(async move {
119                        let chunks = strip_invalid_spans_from_codeblock(response.await?);
120                        futures::pin_mut!(chunks);
121                        let mut diff = StreamingDiff::new(selected_text.to_string());
122
123                        let mut new_text = String::new();
124                        let mut base_indent = None;
125                        let mut line_indent = None;
126                        let mut first_line = true;
127
128                        while let Some(chunk) = chunks.next().await {
129                            let chunk = chunk?;
130
131                            let mut lines = chunk.split('\n').peekable();
132                            while let Some(line) = lines.next() {
133                                new_text.push_str(line);
134                                if line_indent.is_none() {
135                                    if let Some(non_whitespace_ch_ix) =
136                                        new_text.find(|ch: char| !ch.is_whitespace())
137                                    {
138                                        line_indent = Some(non_whitespace_ch_ix);
139                                        base_indent = base_indent.or(line_indent);
140
141                                        let line_indent = line_indent.unwrap();
142                                        let base_indent = base_indent.unwrap();
143                                        let indent_delta = line_indent as i32 - base_indent as i32;
144                                        let mut corrected_indent_len = cmp::max(
145                                            0,
146                                            suggested_line_indent.len as i32 + indent_delta,
147                                        )
148                                            as usize;
149                                        if first_line {
150                                            corrected_indent_len = corrected_indent_len
151                                                .saturating_sub(selection_start.column as usize);
152                                        }
153
154                                        let indent_char = suggested_line_indent.char();
155                                        let mut indent_buffer = [0; 4];
156                                        let indent_str =
157                                            indent_char.encode_utf8(&mut indent_buffer);
158                                        new_text.replace_range(
159                                            ..line_indent,
160                                            &indent_str.repeat(corrected_indent_len),
161                                        );
162                                    }
163                                }
164
165                                if line_indent.is_some() {
166                                    hunks_tx.send(diff.push_new(&new_text)).await?;
167                                    new_text.clear();
168                                }
169
170                                if lines.peek().is_some() {
171                                    hunks_tx.send(diff.push_new("\n")).await?;
172                                    line_indent = None;
173                                    first_line = false;
174                                }
175                            }
176                        }
177                        hunks_tx.send(diff.push_new(&new_text)).await?;
178                        hunks_tx.send(diff.finish()).await?;
179
180                        anyhow::Ok(())
181                    });
182
183                    while let Some(hunks) = hunks_rx.next().await {
184                        this.update(&mut cx, |this, cx| {
185                            this.last_equal_ranges.clear();
186
187                            let transaction = this.buffer.update(cx, |buffer, cx| {
188                                // Avoid grouping assistant edits with user edits.
189                                buffer.finalize_last_transaction(cx);
190
191                                buffer.start_transaction(cx);
192                                buffer.edit(
193                                    hunks.into_iter().filter_map(|hunk| match hunk {
194                                        Hunk::Insert { text } => {
195                                            let edit_start = snapshot.anchor_after(edit_start);
196                                            Some((edit_start..edit_start, text))
197                                        }
198                                        Hunk::Remove { len } => {
199                                            let edit_end = edit_start + len;
200                                            let edit_range = snapshot.anchor_after(edit_start)
201                                                ..snapshot.anchor_before(edit_end);
202                                            edit_start = edit_end;
203                                            Some((edit_range, String::new()))
204                                        }
205                                        Hunk::Keep { len } => {
206                                            let edit_end = edit_start + len;
207                                            let edit_range = snapshot.anchor_after(edit_start)
208                                                ..snapshot.anchor_before(edit_end);
209                                            edit_start = edit_end;
210                                            this.last_equal_ranges.push(edit_range);
211                                            None
212                                        }
213                                    }),
214                                    None,
215                                    cx,
216                                );
217
218                                buffer.end_transaction(cx)
219                            });
220
221                            if let Some(transaction) = transaction {
222                                if let Some(first_transaction) = this.transaction_id {
223                                    // Group all assistant edits into the first transaction.
224                                    this.buffer.update(cx, |buffer, cx| {
225                                        buffer.merge_transactions(
226                                            transaction,
227                                            first_transaction,
228                                            cx,
229                                        )
230                                    });
231                                } else {
232                                    this.transaction_id = Some(transaction);
233                                    this.buffer.update(cx, |buffer, cx| {
234                                        buffer.finalize_last_transaction(cx)
235                                    });
236                                }
237                            }
238
239                            cx.notify();
240                        })?;
241                    }
242
243                    diff.await?;
244                    anyhow::Ok(())
245                };
246
247                let result = generate.await;
248                this.update(&mut cx, |this, cx| {
249                    this.last_equal_ranges.clear();
250                    this.idle = true;
251                    if let Err(error) = result {
252                        this.error = Some(error);
253                    }
254                    cx.emit(Event::Finished);
255                    cx.notify();
256                })
257                .ok();
258            }
259        });
260        self.error.take();
261        self.idle = false;
262        cx.notify();
263    }
264
265    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
266        if let Some(transaction_id) = self.transaction_id {
267            self.buffer
268                .update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
269        }
270    }
271}
272
273fn strip_invalid_spans_from_codeblock(
274    stream: impl Stream<Item = Result<String>>,
275) -> impl Stream<Item = Result<String>> {
276    let mut first_line = true;
277    let mut buffer = String::new();
278    let mut starts_with_markdown_codeblock = false;
279    let mut includes_start_or_end_span = false;
280    stream.filter_map(move |chunk| {
281        let chunk = match chunk {
282            Ok(chunk) => chunk,
283            Err(err) => return future::ready(Some(Err(err))),
284        };
285        buffer.push_str(&chunk);
286
287        if buffer.len() > "<|S|".len() && buffer.starts_with("<|S|") {
288            includes_start_or_end_span = true;
289
290            buffer = buffer
291                .strip_prefix("<|S|>")
292                .or_else(|| buffer.strip_prefix("<|S|"))
293                .unwrap_or(&buffer)
294                .to_string();
295        } else if buffer.ends_with("|E|>") {
296            includes_start_or_end_span = true;
297        } else if buffer.starts_with("<|")
298            || buffer.starts_with("<|S")
299            || buffer.starts_with("<|S|")
300            || buffer.ends_with("|")
301            || buffer.ends_with("|E")
302            || buffer.ends_with("|E|")
303        {
304            return future::ready(None);
305        }
306
307        if first_line {
308            if buffer == "" || buffer == "`" || buffer == "``" {
309                return future::ready(None);
310            } else if buffer.starts_with("```") {
311                starts_with_markdown_codeblock = true;
312                if let Some(newline_ix) = buffer.find('\n') {
313                    buffer.replace_range(..newline_ix + 1, "");
314                    first_line = false;
315                } else {
316                    return future::ready(None);
317                }
318            }
319        }
320
321        let mut text = buffer.to_string();
322        if starts_with_markdown_codeblock {
323            text = text
324                .strip_suffix("\n```\n")
325                .or_else(|| text.strip_suffix("\n```"))
326                .or_else(|| text.strip_suffix("\n``"))
327                .or_else(|| text.strip_suffix("\n`"))
328                .or_else(|| text.strip_suffix('\n'))
329                .unwrap_or(&text)
330                .to_string();
331        }
332
333        if includes_start_or_end_span {
334            text = text
335                .strip_suffix("|E|>")
336                .or_else(|| text.strip_suffix("E|>"))
337                .or_else(|| text.strip_prefix("|>"))
338                .or_else(|| text.strip_prefix(">"))
339                .unwrap_or(&text)
340                .to_string();
341        };
342
343        if text.contains('\n') {
344            first_line = false;
345        }
346
347        let remainder = buffer.split_off(text.len());
348        let result = if buffer.is_empty() {
349            None
350        } else {
351            Some(Ok(buffer.clone()))
352        };
353
354        buffer = remainder;
355        future::ready(result)
356    })
357}
358
359#[cfg(test)]
360mod tests {
361    use std::sync::Arc;
362
363    use super::*;
364    use ai::test::FakeCompletionProvider;
365    use futures::stream::{self};
366    use gpui::{Context, TestAppContext};
367    use indoc::indoc;
368    use language::{language_settings, tree_sitter_rust, Buffer, Language, LanguageConfig, Point};
369    use rand::prelude::*;
370    use serde::Serialize;
371    use settings::SettingsStore;
372
373    #[derive(Serialize)]
374    pub struct DummyCompletionRequest {
375        pub name: String,
376    }
377
378    impl CompletionRequest for DummyCompletionRequest {
379        fn data(&self) -> serde_json::Result<String> {
380            serde_json::to_string(self)
381        }
382    }
383
384    #[gpui::test(iterations = 10)]
385    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
386        cx.set_global(cx.update(SettingsStore::test));
387        cx.update(language_settings::init);
388
389        let text = indoc! {"
390            fn main() {
391                let x = 0;
392                for _ in 0..10 {
393                    x += 1;
394                }
395            }
396        "};
397        let buffer =
398            cx.build_model(|cx| Buffer::new(0, 0, text).with_language(Arc::new(rust_lang()), cx));
399        let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
400        let range = buffer.read_with(cx, |buffer, cx| {
401            let snapshot = buffer.snapshot(cx);
402            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
403        });
404        let provider = Arc::new(FakeCompletionProvider::new());
405        let codegen = cx.build_model(|cx| {
406            Codegen::new(
407                buffer.clone(),
408                CodegenKind::Transform { range },
409                provider.clone(),
410                cx,
411            )
412        });
413
414        let request = Box::new(DummyCompletionRequest {
415            name: "test".to_string(),
416        });
417        codegen.update(cx, |codegen, cx| codegen.start(request, cx));
418
419        let mut new_text = concat!(
420            "       let mut x = 0;\n",
421            "       while x < 10 {\n",
422            "           x += 1;\n",
423            "       }",
424        );
425        while !new_text.is_empty() {
426            let max_len = cmp::min(new_text.len(), 10);
427            let len = rng.gen_range(1..=max_len);
428            let (chunk, suffix) = new_text.split_at(len);
429            println!("CHUNK: {:?}", &chunk);
430            provider.send_completion(chunk);
431            new_text = suffix;
432            cx.background_executor.run_until_parked();
433        }
434        provider.finish_completion();
435        cx.background_executor.run_until_parked();
436
437        assert_eq!(
438            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
439            indoc! {"
440                fn main() {
441                    let mut x = 0;
442                    while x < 10 {
443                        x += 1;
444                    }
445                }
446            "}
447        );
448    }
449
450    #[gpui::test(iterations = 10)]
451    async fn test_autoindent_when_generating_past_indentation(
452        cx: &mut TestAppContext,
453        mut rng: StdRng,
454    ) {
455        cx.set_global(cx.update(SettingsStore::test));
456        cx.update(language_settings::init);
457
458        let text = indoc! {"
459            fn main() {
460                le
461            }
462        "};
463        let buffer =
464            cx.build_model(|cx| Buffer::new(0, 0, text).with_language(Arc::new(rust_lang()), cx));
465        let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
466        let position = buffer.read_with(cx, |buffer, cx| {
467            let snapshot = buffer.snapshot(cx);
468            snapshot.anchor_before(Point::new(1, 6))
469        });
470        let provider = Arc::new(FakeCompletionProvider::new());
471        let codegen = cx.build_model(|cx| {
472            Codegen::new(
473                buffer.clone(),
474                CodegenKind::Generate { position },
475                provider.clone(),
476                cx,
477            )
478        });
479
480        let request = Box::new(DummyCompletionRequest {
481            name: "test".to_string(),
482        });
483        codegen.update(cx, |codegen, cx| codegen.start(request, cx));
484
485        let mut new_text = concat!(
486            "t mut x = 0;\n",
487            "while x < 10 {\n",
488            "    x += 1;\n",
489            "}", //
490        );
491        while !new_text.is_empty() {
492            let max_len = cmp::min(new_text.len(), 10);
493            let len = rng.gen_range(1..=max_len);
494            let (chunk, suffix) = new_text.split_at(len);
495            provider.send_completion(chunk);
496            new_text = suffix;
497            cx.background_executor.run_until_parked();
498        }
499        provider.finish_completion();
500        cx.background_executor.run_until_parked();
501
502        assert_eq!(
503            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
504            indoc! {"
505                fn main() {
506                    let mut x = 0;
507                    while x < 10 {
508                        x += 1;
509                    }
510                }
511            "}
512        );
513    }
514
515    #[gpui::test(iterations = 10)]
516    async fn test_autoindent_when_generating_before_indentation(
517        cx: &mut TestAppContext,
518        mut rng: StdRng,
519    ) {
520        cx.set_global(cx.update(SettingsStore::test));
521        cx.update(language_settings::init);
522
523        let text = concat!(
524            "fn main() {\n",
525            "  \n",
526            "}\n" //
527        );
528        let buffer =
529            cx.build_model(|cx| Buffer::new(0, 0, text).with_language(Arc::new(rust_lang()), cx));
530        let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
531        let position = buffer.read_with(cx, |buffer, cx| {
532            let snapshot = buffer.snapshot(cx);
533            snapshot.anchor_before(Point::new(1, 2))
534        });
535        let provider = Arc::new(FakeCompletionProvider::new());
536        let codegen = cx.build_model(|cx| {
537            Codegen::new(
538                buffer.clone(),
539                CodegenKind::Generate { position },
540                provider.clone(),
541                cx,
542            )
543        });
544
545        let request = Box::new(DummyCompletionRequest {
546            name: "test".to_string(),
547        });
548        codegen.update(cx, |codegen, cx| codegen.start(request, cx));
549
550        let mut new_text = concat!(
551            "let mut x = 0;\n",
552            "while x < 10 {\n",
553            "    x += 1;\n",
554            "}", //
555        );
556        while !new_text.is_empty() {
557            let max_len = cmp::min(new_text.len(), 10);
558            let len = rng.gen_range(1..=max_len);
559            let (chunk, suffix) = new_text.split_at(len);
560            println!("{:?}", &chunk);
561            provider.send_completion(chunk);
562            new_text = suffix;
563            cx.background_executor.run_until_parked();
564        }
565        provider.finish_completion();
566        cx.background_executor.run_until_parked();
567
568        assert_eq!(
569            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
570            indoc! {"
571                fn main() {
572                    let mut x = 0;
573                    while x < 10 {
574                        x += 1;
575                    }
576                }
577            "}
578        );
579    }
580
581    #[gpui::test]
582    async fn test_strip_invalid_spans_from_codeblock() {
583        assert_eq!(
584            strip_invalid_spans_from_codeblock(chunks("Lorem ipsum dolor", 2))
585                .map(|chunk| chunk.unwrap())
586                .collect::<String>()
587                .await,
588            "Lorem ipsum dolor"
589        );
590        assert_eq!(
591            strip_invalid_spans_from_codeblock(chunks("```\nLorem ipsum dolor", 2))
592                .map(|chunk| chunk.unwrap())
593                .collect::<String>()
594                .await,
595            "Lorem ipsum dolor"
596        );
597        assert_eq!(
598            strip_invalid_spans_from_codeblock(chunks("```\nLorem ipsum dolor\n```", 2))
599                .map(|chunk| chunk.unwrap())
600                .collect::<String>()
601                .await,
602            "Lorem ipsum dolor"
603        );
604        assert_eq!(
605            strip_invalid_spans_from_codeblock(chunks("```\nLorem ipsum dolor\n```\n", 2))
606                .map(|chunk| chunk.unwrap())
607                .collect::<String>()
608                .await,
609            "Lorem ipsum dolor"
610        );
611        assert_eq!(
612            strip_invalid_spans_from_codeblock(chunks(
613                "```html\n```js\nLorem ipsum dolor\n```\n```",
614                2
615            ))
616            .map(|chunk| chunk.unwrap())
617            .collect::<String>()
618            .await,
619            "```js\nLorem ipsum dolor\n```"
620        );
621        assert_eq!(
622            strip_invalid_spans_from_codeblock(chunks("``\nLorem ipsum dolor\n```", 2))
623                .map(|chunk| chunk.unwrap())
624                .collect::<String>()
625                .await,
626            "``\nLorem ipsum dolor\n```"
627        );
628        assert_eq!(
629            strip_invalid_spans_from_codeblock(chunks("<|S|Lorem ipsum|E|>", 2))
630                .map(|chunk| chunk.unwrap())
631                .collect::<String>()
632                .await,
633            "Lorem ipsum"
634        );
635
636        assert_eq!(
637            strip_invalid_spans_from_codeblock(chunks("<|S|>Lorem ipsum", 2))
638                .map(|chunk| chunk.unwrap())
639                .collect::<String>()
640                .await,
641            "Lorem ipsum"
642        );
643
644        assert_eq!(
645            strip_invalid_spans_from_codeblock(chunks("```\n<|S|>Lorem ipsum\n```", 2))
646                .map(|chunk| chunk.unwrap())
647                .collect::<String>()
648                .await,
649            "Lorem ipsum"
650        );
651        assert_eq!(
652            strip_invalid_spans_from_codeblock(chunks("```\n<|S|Lorem ipsum|E|>\n```", 2))
653                .map(|chunk| chunk.unwrap())
654                .collect::<String>()
655                .await,
656            "Lorem ipsum"
657        );
658        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
659            stream::iter(
660                text.chars()
661                    .collect::<Vec<_>>()
662                    .chunks(size)
663                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
664                    .collect::<Vec<_>>(),
665            )
666        }
667    }
668
669    fn rust_lang() -> Language {
670        Language::new(
671            LanguageConfig {
672                name: "Rust".into(),
673                path_suffixes: vec!["rs".to_string()],
674                ..Default::default()
675            },
676            Some(tree_sitter_rust::language()),
677        )
678        .with_indents_query(
679            r#"
680            (call_expression) @indent
681            (field_expression) @indent
682            (_ "(" ")" @end) @indent
683            (_ "{" "}" @end) @indent
684            "#,
685        )
686        .unwrap()
687    }
688}