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