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 let this = if let Some(this) = this.upgrade() {
185 this
186 } else {
187 break;
188 };
189
190 this.update(&mut cx, |this, cx| {
191 this.last_equal_ranges.clear();
192
193 let transaction = this.buffer.update(cx, |buffer, cx| {
194 // Avoid grouping assistant edits with user edits.
195 buffer.finalize_last_transaction(cx);
196
197 buffer.start_transaction(cx);
198 buffer.edit(
199 hunks.into_iter().filter_map(|hunk| match hunk {
200 Hunk::Insert { text } => {
201 let edit_start = snapshot.anchor_after(edit_start);
202 Some((edit_start..edit_start, text))
203 }
204 Hunk::Remove { len } => {
205 let edit_end = edit_start + len;
206 let edit_range = snapshot.anchor_after(edit_start)
207 ..snapshot.anchor_before(edit_end);
208 edit_start = edit_end;
209 Some((edit_range, String::new()))
210 }
211 Hunk::Keep { len } => {
212 let edit_end = edit_start + len;
213 let edit_range = snapshot.anchor_after(edit_start)
214 ..snapshot.anchor_before(edit_end);
215 edit_start = edit_end;
216 this.last_equal_ranges.push(edit_range);
217 None
218 }
219 }),
220 None,
221 cx,
222 );
223
224 buffer.end_transaction(cx)
225 });
226
227 if let Some(transaction) = transaction {
228 if let Some(first_transaction) = this.transaction_id {
229 // Group all assistant edits into the first transaction.
230 this.buffer.update(cx, |buffer, cx| {
231 buffer.merge_transactions(
232 transaction,
233 first_transaction,
234 cx,
235 )
236 });
237 } else {
238 this.transaction_id = Some(transaction);
239 this.buffer.update(cx, |buffer, cx| {
240 buffer.finalize_last_transaction(cx)
241 });
242 }
243 }
244
245 cx.notify();
246 });
247 }
248
249 diff.await?;
250 anyhow::Ok(())
251 };
252
253 let result = generate.await;
254 this.update(&mut cx, |this, cx| {
255 this.last_equal_ranges.clear();
256 this.idle = true;
257 if let Err(error) = result {
258 this.error = Some(error);
259 }
260 cx.emit(Event::Finished);
261 cx.notify();
262 })
263 .ok();
264 }
265 });
266 self.error.take();
267 self.idle = false;
268 cx.notify();
269 }
270
271 pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
272 if let Some(transaction_id) = self.transaction_id {
273 self.buffer
274 .update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
275 }
276 }
277}
278
279fn strip_invalid_spans_from_codeblock(
280 stream: impl Stream<Item = Result<String>>,
281) -> impl Stream<Item = Result<String>> {
282 let mut first_line = true;
283 let mut buffer = String::new();
284 let mut starts_with_markdown_codeblock = false;
285 let mut includes_start_or_end_span = false;
286 stream.filter_map(move |chunk| {
287 let chunk = match chunk {
288 Ok(chunk) => chunk,
289 Err(err) => return future::ready(Some(Err(err))),
290 };
291 buffer.push_str(&chunk);
292
293 if buffer.len() > "<|S|".len() && buffer.starts_with("<|S|") {
294 includes_start_or_end_span = true;
295
296 buffer = buffer
297 .strip_prefix("<|S|>")
298 .or_else(|| buffer.strip_prefix("<|S|"))
299 .unwrap_or(&buffer)
300 .to_string();
301 } else if buffer.ends_with("|E|>") {
302 includes_start_or_end_span = true;
303 } else if buffer.starts_with("<|")
304 || buffer.starts_with("<|S")
305 || buffer.starts_with("<|S|")
306 || buffer.ends_with("|")
307 || buffer.ends_with("|E")
308 || buffer.ends_with("|E|")
309 {
310 return future::ready(None);
311 }
312
313 if first_line {
314 if buffer == "" || buffer == "`" || buffer == "``" {
315 return future::ready(None);
316 } else if buffer.starts_with("```") {
317 starts_with_markdown_codeblock = true;
318 if let Some(newline_ix) = buffer.find('\n') {
319 buffer.replace_range(..newline_ix + 1, "");
320 first_line = false;
321 } else {
322 return future::ready(None);
323 }
324 }
325 }
326
327 let mut text = buffer.to_string();
328 if starts_with_markdown_codeblock {
329 text = text
330 .strip_suffix("\n```\n")
331 .or_else(|| text.strip_suffix("\n```"))
332 .or_else(|| text.strip_suffix("\n``"))
333 .or_else(|| text.strip_suffix("\n`"))
334 .or_else(|| text.strip_suffix('\n'))
335 .unwrap_or(&text)
336 .to_string();
337 }
338
339 if includes_start_or_end_span {
340 text = text
341 .strip_suffix("|E|>")
342 .or_else(|| text.strip_suffix("E|>"))
343 .or_else(|| text.strip_prefix("|>"))
344 .or_else(|| text.strip_prefix(">"))
345 .unwrap_or(&text)
346 .to_string();
347 };
348
349 if text.contains('\n') {
350 first_line = false;
351 }
352
353 let remainder = buffer.split_off(text.len());
354 let result = if buffer.is_empty() {
355 None
356 } else {
357 Some(Ok(buffer.clone()))
358 };
359
360 buffer = remainder;
361 future::ready(result)
362 })
363}
364
365#[cfg(test)]
366mod tests {
367 use std::sync::Arc;
368
369 use super::*;
370 use ai::test::FakeCompletionProvider;
371 use futures::stream::{self};
372 use gpui::{Context, TestAppContext};
373 use indoc::indoc;
374 use language::{language_settings, tree_sitter_rust, Buffer, Language, LanguageConfig, Point};
375 use rand::prelude::*;
376 use serde::Serialize;
377 use settings::SettingsStore;
378
379 #[derive(Serialize)]
380 pub struct DummyCompletionRequest {
381 pub name: String,
382 }
383
384 impl CompletionRequest for DummyCompletionRequest {
385 fn data(&self) -> serde_json::Result<String> {
386 serde_json::to_string(self)
387 }
388 }
389
390 #[gpui::test(iterations = 10)]
391 async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
392 cx.set_global(cx.update(SettingsStore::test));
393 cx.update(language_settings::init);
394
395 let text = indoc! {"
396 fn main() {
397 let x = 0;
398 for _ in 0..10 {
399 x += 1;
400 }
401 }
402 "};
403 let buffer =
404 cx.build_model(|cx| Buffer::new(0, 0, text).with_language(Arc::new(rust_lang()), cx));
405 let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
406 let range = buffer.read_with(cx, |buffer, cx| {
407 let snapshot = buffer.snapshot(cx);
408 snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
409 });
410 let provider = Arc::new(FakeCompletionProvider::new());
411 let codegen = cx.build_model(|cx| {
412 Codegen::new(
413 buffer.clone(),
414 CodegenKind::Transform { range },
415 provider.clone(),
416 cx,
417 )
418 });
419
420 let request = Box::new(DummyCompletionRequest {
421 name: "test".to_string(),
422 });
423 codegen.update(cx, |codegen, cx| codegen.start(request, cx));
424
425 let mut new_text = concat!(
426 " let mut x = 0;\n",
427 " while x < 10 {\n",
428 " x += 1;\n",
429 " }",
430 );
431 while !new_text.is_empty() {
432 let max_len = cmp::min(new_text.len(), 10);
433 let len = rng.gen_range(1..=max_len);
434 let (chunk, suffix) = new_text.split_at(len);
435 println!("CHUNK: {:?}", &chunk);
436 provider.send_completion(chunk);
437 new_text = suffix;
438 cx.background_executor.run_until_parked();
439 }
440 provider.finish_completion();
441 cx.background_executor.run_until_parked();
442
443 assert_eq!(
444 buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
445 indoc! {"
446 fn main() {
447 let mut x = 0;
448 while x < 10 {
449 x += 1;
450 }
451 }
452 "}
453 );
454 }
455
456 #[gpui::test(iterations = 10)]
457 async fn test_autoindent_when_generating_past_indentation(
458 cx: &mut TestAppContext,
459 mut rng: StdRng,
460 ) {
461 cx.set_global(cx.update(SettingsStore::test));
462 cx.update(language_settings::init);
463
464 let text = indoc! {"
465 fn main() {
466 le
467 }
468 "};
469 let buffer =
470 cx.build_model(|cx| Buffer::new(0, 0, text).with_language(Arc::new(rust_lang()), cx));
471 let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
472 let position = buffer.read_with(cx, |buffer, cx| {
473 let snapshot = buffer.snapshot(cx);
474 snapshot.anchor_before(Point::new(1, 6))
475 });
476 let provider = Arc::new(FakeCompletionProvider::new());
477 let codegen = cx.build_model(|cx| {
478 Codegen::new(
479 buffer.clone(),
480 CodegenKind::Generate { position },
481 provider.clone(),
482 cx,
483 )
484 });
485
486 let request = Box::new(DummyCompletionRequest {
487 name: "test".to_string(),
488 });
489 codegen.update(cx, |codegen, cx| codegen.start(request, cx));
490
491 let mut new_text = concat!(
492 "t mut x = 0;\n",
493 "while x < 10 {\n",
494 " x += 1;\n",
495 "}", //
496 );
497 while !new_text.is_empty() {
498 let max_len = cmp::min(new_text.len(), 10);
499 let len = rng.gen_range(1..=max_len);
500 let (chunk, suffix) = new_text.split_at(len);
501 provider.send_completion(chunk);
502 new_text = suffix;
503 cx.background_executor.run_until_parked();
504 }
505 provider.finish_completion();
506 cx.background_executor.run_until_parked();
507
508 assert_eq!(
509 buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
510 indoc! {"
511 fn main() {
512 let mut x = 0;
513 while x < 10 {
514 x += 1;
515 }
516 }
517 "}
518 );
519 }
520
521 #[gpui::test(iterations = 10)]
522 async fn test_autoindent_when_generating_before_indentation(
523 cx: &mut TestAppContext,
524 mut rng: StdRng,
525 ) {
526 cx.set_global(cx.update(SettingsStore::test));
527 cx.update(language_settings::init);
528
529 let text = concat!(
530 "fn main() {\n",
531 " \n",
532 "}\n" //
533 );
534 let buffer =
535 cx.build_model(|cx| Buffer::new(0, 0, text).with_language(Arc::new(rust_lang()), cx));
536 let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
537 let position = buffer.read_with(cx, |buffer, cx| {
538 let snapshot = buffer.snapshot(cx);
539 snapshot.anchor_before(Point::new(1, 2))
540 });
541 let provider = Arc::new(FakeCompletionProvider::new());
542 let codegen = cx.build_model(|cx| {
543 Codegen::new(
544 buffer.clone(),
545 CodegenKind::Generate { position },
546 provider.clone(),
547 cx,
548 )
549 });
550
551 let request = Box::new(DummyCompletionRequest {
552 name: "test".to_string(),
553 });
554 codegen.update(cx, |codegen, cx| codegen.start(request, cx));
555
556 let mut new_text = concat!(
557 "let mut x = 0;\n",
558 "while x < 10 {\n",
559 " x += 1;\n",
560 "}", //
561 );
562 while !new_text.is_empty() {
563 let max_len = cmp::min(new_text.len(), 10);
564 let len = rng.gen_range(1..=max_len);
565 let (chunk, suffix) = new_text.split_at(len);
566 println!("{:?}", &chunk);
567 provider.send_completion(chunk);
568 new_text = suffix;
569 cx.background_executor.run_until_parked();
570 }
571 provider.finish_completion();
572 cx.background_executor.run_until_parked();
573
574 assert_eq!(
575 buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
576 indoc! {"
577 fn main() {
578 let mut x = 0;
579 while x < 10 {
580 x += 1;
581 }
582 }
583 "}
584 );
585 }
586
587 #[gpui::test]
588 async fn test_strip_invalid_spans_from_codeblock() {
589 assert_eq!(
590 strip_invalid_spans_from_codeblock(chunks("Lorem ipsum dolor", 2))
591 .map(|chunk| chunk.unwrap())
592 .collect::<String>()
593 .await,
594 "Lorem ipsum dolor"
595 );
596 assert_eq!(
597 strip_invalid_spans_from_codeblock(chunks("```\nLorem ipsum dolor", 2))
598 .map(|chunk| chunk.unwrap())
599 .collect::<String>()
600 .await,
601 "Lorem ipsum dolor"
602 );
603 assert_eq!(
604 strip_invalid_spans_from_codeblock(chunks("```\nLorem ipsum dolor\n```", 2))
605 .map(|chunk| chunk.unwrap())
606 .collect::<String>()
607 .await,
608 "Lorem ipsum dolor"
609 );
610 assert_eq!(
611 strip_invalid_spans_from_codeblock(chunks("```\nLorem ipsum dolor\n```\n", 2))
612 .map(|chunk| chunk.unwrap())
613 .collect::<String>()
614 .await,
615 "Lorem ipsum dolor"
616 );
617 assert_eq!(
618 strip_invalid_spans_from_codeblock(chunks(
619 "```html\n```js\nLorem ipsum dolor\n```\n```",
620 2
621 ))
622 .map(|chunk| chunk.unwrap())
623 .collect::<String>()
624 .await,
625 "```js\nLorem ipsum dolor\n```"
626 );
627 assert_eq!(
628 strip_invalid_spans_from_codeblock(chunks("``\nLorem ipsum dolor\n```", 2))
629 .map(|chunk| chunk.unwrap())
630 .collect::<String>()
631 .await,
632 "``\nLorem ipsum dolor\n```"
633 );
634 assert_eq!(
635 strip_invalid_spans_from_codeblock(chunks("<|S|Lorem ipsum|E|>", 2))
636 .map(|chunk| chunk.unwrap())
637 .collect::<String>()
638 .await,
639 "Lorem ipsum"
640 );
641
642 assert_eq!(
643 strip_invalid_spans_from_codeblock(chunks("<|S|>Lorem ipsum", 2))
644 .map(|chunk| chunk.unwrap())
645 .collect::<String>()
646 .await,
647 "Lorem ipsum"
648 );
649
650 assert_eq!(
651 strip_invalid_spans_from_codeblock(chunks("```\n<|S|>Lorem ipsum\n```", 2))
652 .map(|chunk| chunk.unwrap())
653 .collect::<String>()
654 .await,
655 "Lorem ipsum"
656 );
657 assert_eq!(
658 strip_invalid_spans_from_codeblock(chunks("```\n<|S|Lorem ipsum|E|>\n```", 2))
659 .map(|chunk| chunk.unwrap())
660 .collect::<String>()
661 .await,
662 "Lorem ipsum"
663 );
664 fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
665 stream::iter(
666 text.chars()
667 .collect::<Vec<_>>()
668 .chunks(size)
669 .map(|chunk| Ok(chunk.iter().collect::<String>()))
670 .collect::<Vec<_>>(),
671 )
672 }
673 }
674
675 fn rust_lang() -> Language {
676 Language::new(
677 LanguageConfig {
678 name: "Rust".into(),
679 path_suffixes: vec!["rs".to_string()],
680 ..Default::default()
681 },
682 Some(tree_sitter_rust::language()),
683 )
684 .with_indents_query(
685 r#"
686 (call_expression) @indent
687 (field_expression) @indent
688 (_ "(" ")" @end) @indent
689 (_ "{" "}" @end) @indent
690 "#,
691 )
692 .unwrap()
693 }
694}