1use std::cmp;
2use std::mem;
3use std::ops::Range;
4use std::rc::Rc;
5use std::sync::Arc;
6
7use anyhow::{Context as _, Result};
8use assistant_settings::AssistantSettings;
9use client::telemetry::Telemetry;
10use collections::{hash_map, HashMap, HashSet, VecDeque};
11use editor::{
12 actions::SelectAll,
13 display_map::{
14 BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock,
15 ToDisplayPoint,
16 },
17 Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorEvent, ExcerptId, ExcerptRange,
18 GutterDimensions, MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint,
19};
20use feature_flags::{Assistant2FeatureFlag, FeatureFlagViewExt as _};
21use fs::Fs;
22use gpui::{
23 point, App, Context, Entity, Focusable, Global, HighlightStyle, Subscription, Task,
24 UpdateGlobal, WeakEntity, Window,
25};
26use language::{Buffer, Point, Selection, TransactionId};
27use language_model::{report_assistant_event, LanguageModelRegistry};
28use multi_buffer::MultiBufferRow;
29use parking_lot::Mutex;
30use project::{CodeAction, ProjectTransaction};
31use prompt_store::PromptBuilder;
32use settings::{Settings, SettingsStore};
33use telemetry_events::{AssistantEvent, AssistantKind, AssistantPhase};
34use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
35use text::{OffsetRangeExt, ToPoint as _};
36use ui::prelude::*;
37use util::RangeExt;
38use util::ResultExt;
39use workspace::{dock::Panel, ShowConfiguration};
40use workspace::{notifications::NotificationId, ItemHandle, Toast, Workspace};
41
42use crate::buffer_codegen::{BufferCodegen, CodegenAlternative, CodegenEvent};
43use crate::context_store::ContextStore;
44use crate::inline_prompt_editor::{CodegenStatus, InlineAssistId, PromptEditor, PromptEditorEvent};
45use crate::terminal_inline_assistant::TerminalInlineAssistant;
46use crate::thread_store::ThreadStore;
47use crate::AssistantPanel;
48
49pub fn init(
50 fs: Arc<dyn Fs>,
51 prompt_builder: Arc<PromptBuilder>,
52 telemetry: Arc<Telemetry>,
53 cx: &mut App,
54) {
55 cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));
56 cx.observe_new(|_workspace: &mut Workspace, window, cx| {
57 let Some(window) = window else {
58 return;
59 };
60 let workspace = cx.entity().clone();
61 InlineAssistant::update_global(cx, |inline_assistant, cx| {
62 inline_assistant.register_workspace(&workspace, window, cx)
63 });
64
65 cx.observe_flag::<Assistant2FeatureFlag, _>(window, {
66 |is_assistant2_enabled, _workspace, _window, cx| {
67 InlineAssistant::update_global(cx, |inline_assistant, _cx| {
68 inline_assistant.is_assistant2_enabled = is_assistant2_enabled;
69 });
70 }
71 })
72 .detach();
73 })
74 .detach();
75}
76
77const PROMPT_HISTORY_MAX_LEN: usize = 20;
78
79enum InlineAssistTarget {
80 Editor(Entity<Editor>),
81 Terminal(Entity<TerminalView>),
82}
83
84pub struct InlineAssistant {
85 next_assist_id: InlineAssistId,
86 next_assist_group_id: InlineAssistGroupId,
87 assists: HashMap<InlineAssistId, InlineAssist>,
88 assists_by_editor: HashMap<WeakEntity<Editor>, EditorInlineAssists>,
89 assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,
90 confirmed_assists: HashMap<InlineAssistId, Entity<CodegenAlternative>>,
91 prompt_history: VecDeque<String>,
92 prompt_builder: Arc<PromptBuilder>,
93 telemetry: Arc<Telemetry>,
94 fs: Arc<dyn Fs>,
95 is_assistant2_enabled: bool,
96}
97
98impl Global for InlineAssistant {}
99
100impl InlineAssistant {
101 pub fn new(
102 fs: Arc<dyn Fs>,
103 prompt_builder: Arc<PromptBuilder>,
104 telemetry: Arc<Telemetry>,
105 ) -> Self {
106 Self {
107 next_assist_id: InlineAssistId::default(),
108 next_assist_group_id: InlineAssistGroupId::default(),
109 assists: HashMap::default(),
110 assists_by_editor: HashMap::default(),
111 assist_groups: HashMap::default(),
112 confirmed_assists: HashMap::default(),
113 prompt_history: VecDeque::default(),
114 prompt_builder,
115 telemetry,
116 fs,
117 is_assistant2_enabled: false,
118 }
119 }
120
121 pub fn register_workspace(
122 &mut self,
123 workspace: &Entity<Workspace>,
124 window: &mut Window,
125 cx: &mut App,
126 ) {
127 window
128 .subscribe(workspace, cx, |workspace, event, window, cx| {
129 Self::update_global(cx, |this, cx| {
130 this.handle_workspace_event(workspace, event, window, cx)
131 });
132 })
133 .detach();
134
135 let workspace = workspace.downgrade();
136 cx.observe_global::<SettingsStore>(move |cx| {
137 let Some(workspace) = workspace.upgrade() else {
138 return;
139 };
140 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
141 return;
142 };
143 let enabled = AssistantSettings::get_global(cx).enabled;
144 terminal_panel.update(cx, |terminal_panel, cx| {
145 terminal_panel.set_assistant_enabled(enabled, cx)
146 });
147 })
148 .detach();
149 }
150
151 fn handle_workspace_event(
152 &mut self,
153 workspace: Entity<Workspace>,
154 event: &workspace::Event,
155 window: &mut Window,
156 cx: &mut App,
157 ) {
158 match event {
159 workspace::Event::UserSavedItem { item, .. } => {
160 // When the user manually saves an editor, automatically accepts all finished transformations.
161 if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx)) {
162 if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
163 for assist_id in editor_assists.assist_ids.clone() {
164 let assist = &self.assists[&assist_id];
165 if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
166 self.finish_assist(assist_id, false, window, cx)
167 }
168 }
169 }
170 }
171 }
172 workspace::Event::ItemAdded { item } => {
173 self.register_workspace_item(&workspace, item.as_ref(), window, cx);
174 }
175 _ => (),
176 }
177 }
178
179 fn register_workspace_item(
180 &mut self,
181 workspace: &Entity<Workspace>,
182 item: &dyn ItemHandle,
183 window: &mut Window,
184 cx: &mut App,
185 ) {
186 let is_assistant2_enabled = self.is_assistant2_enabled;
187
188 if let Some(editor) = item.act_as::<Editor>(cx) {
189 editor.update(cx, |editor, cx| {
190 if is_assistant2_enabled {
191 let thread_store = workspace
192 .read(cx)
193 .panel::<AssistantPanel>(cx)
194 .map(|assistant_panel| assistant_panel.read(cx).thread_store().downgrade());
195
196 editor.add_code_action_provider(
197 Rc::new(AssistantCodeActionProvider {
198 editor: cx.entity().downgrade(),
199 workspace: workspace.downgrade(),
200 thread_store,
201 }),
202 window,
203 cx,
204 );
205
206 // Remove the Assistant1 code action provider, as it still might be registered.
207 editor.remove_code_action_provider("assistant".into(), window, cx);
208 } else {
209 editor.remove_code_action_provider(
210 ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
211 window,
212 cx,
213 );
214 }
215 });
216 }
217 }
218
219 pub fn inline_assist(
220 workspace: &mut Workspace,
221 _action: &zed_actions::assistant::InlineAssist,
222 window: &mut Window,
223 cx: &mut Context<Workspace>,
224 ) {
225 let settings = AssistantSettings::get_global(cx);
226 if !settings.enabled {
227 return;
228 }
229
230 let Some(inline_assist_target) = Self::resolve_inline_assist_target(
231 workspace,
232 workspace.panel::<AssistantPanel>(cx),
233 window,
234 cx,
235 ) else {
236 return;
237 };
238
239 let is_authenticated = || {
240 LanguageModelRegistry::read_global(cx)
241 .active_provider()
242 .map_or(false, |provider| provider.is_authenticated(cx))
243 };
244
245 let thread_store = workspace
246 .panel::<AssistantPanel>(cx)
247 .map(|assistant_panel| assistant_panel.read(cx).thread_store().downgrade());
248
249 let handle_assist =
250 |window: &mut Window, cx: &mut Context<Workspace>| match inline_assist_target {
251 InlineAssistTarget::Editor(active_editor) => {
252 InlineAssistant::update_global(cx, |assistant, cx| {
253 assistant.assist(
254 &active_editor,
255 cx.entity().downgrade(),
256 thread_store,
257 window,
258 cx,
259 )
260 })
261 }
262 InlineAssistTarget::Terminal(active_terminal) => {
263 TerminalInlineAssistant::update_global(cx, |assistant, cx| {
264 assistant.assist(
265 &active_terminal,
266 cx.entity().downgrade(),
267 thread_store,
268 window,
269 cx,
270 )
271 })
272 }
273 };
274
275 if is_authenticated() {
276 handle_assist(window, cx);
277 } else {
278 cx.spawn_in(window, |_workspace, mut cx| async move {
279 let Some(task) = cx.update(|_, cx| {
280 LanguageModelRegistry::read_global(cx)
281 .active_provider()
282 .map_or(None, |provider| Some(provider.authenticate(cx)))
283 })?
284 else {
285 let answer = cx
286 .prompt(
287 gpui::PromptLevel::Warning,
288 "No language model provider configured",
289 None,
290 &["Configure", "Cancel"],
291 )
292 .await
293 .ok();
294 if let Some(answer) = answer {
295 if answer == 0 {
296 cx.update(|window, cx| {
297 window.dispatch_action(Box::new(ShowConfiguration), cx)
298 })
299 .ok();
300 }
301 }
302 return Ok(());
303 };
304 task.await?;
305
306 anyhow::Ok(())
307 })
308 .detach_and_log_err(cx);
309
310 if is_authenticated() {
311 handle_assist(window, cx);
312 }
313 }
314 }
315
316 pub fn assist(
317 &mut self,
318 editor: &Entity<Editor>,
319 workspace: WeakEntity<Workspace>,
320 thread_store: Option<WeakEntity<ThreadStore>>,
321 window: &mut Window,
322 cx: &mut App,
323 ) {
324 let (snapshot, initial_selections) = editor.update(cx, |editor, cx| {
325 (
326 editor.buffer().read(cx).snapshot(cx),
327 editor.selections.all::<Point>(cx),
328 )
329 });
330
331 let mut selections = Vec::<Selection<Point>>::new();
332 let mut newest_selection = None;
333 for mut selection in initial_selections {
334 if selection.end > selection.start {
335 selection.start.column = 0;
336 // If the selection ends at the start of the line, we don't want to include it.
337 if selection.end.column == 0 {
338 selection.end.row -= 1;
339 }
340 selection.end.column = snapshot.line_len(MultiBufferRow(selection.end.row));
341 }
342
343 if let Some(prev_selection) = selections.last_mut() {
344 if selection.start <= prev_selection.end {
345 prev_selection.end = selection.end;
346 continue;
347 }
348 }
349
350 let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
351 if selection.id > latest_selection.id {
352 *latest_selection = selection.clone();
353 }
354 selections.push(selection);
355 }
356 let newest_selection = newest_selection.unwrap();
357
358 let mut codegen_ranges = Vec::new();
359 for (buffer, buffer_range, excerpt_id) in
360 snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
361 snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
362 }))
363 {
364 let anchor_range = Anchor::range_in_buffer(
365 excerpt_id,
366 buffer.remote_id(),
367 buffer.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
368 );
369
370 codegen_ranges.push(anchor_range);
371
372 if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
373 self.telemetry.report_assistant_event(AssistantEvent {
374 conversation_id: None,
375 kind: AssistantKind::Inline,
376 phase: AssistantPhase::Invoked,
377 message_id: None,
378 model: model.telemetry_id(),
379 model_provider: model.provider_id().to_string(),
380 response_latency: None,
381 error_message: None,
382 language_name: buffer.language().map(|language| language.name().to_proto()),
383 });
384 }
385 }
386
387 let assist_group_id = self.next_assist_group_id.post_inc();
388 let prompt_buffer =
389 cx.new(|cx| MultiBuffer::singleton(cx.new(|cx| Buffer::local(String::new(), cx)), cx));
390
391 let mut assists = Vec::new();
392 let mut assist_to_focus = None;
393 for range in codegen_ranges {
394 let assist_id = self.next_assist_id.post_inc();
395 let context_store = cx.new(|_cx| ContextStore::new(workspace.clone()));
396 let codegen = cx.new(|cx| {
397 BufferCodegen::new(
398 editor.read(cx).buffer().clone(),
399 range.clone(),
400 None,
401 context_store.clone(),
402 self.telemetry.clone(),
403 self.prompt_builder.clone(),
404 cx,
405 )
406 });
407
408 let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
409 let prompt_editor = cx.new(|cx| {
410 PromptEditor::new_buffer(
411 assist_id,
412 gutter_dimensions.clone(),
413 self.prompt_history.clone(),
414 prompt_buffer.clone(),
415 codegen.clone(),
416 self.fs.clone(),
417 context_store,
418 workspace.clone(),
419 thread_store.clone(),
420 window,
421 cx,
422 )
423 });
424
425 if assist_to_focus.is_none() {
426 let focus_assist = if newest_selection.reversed {
427 range.start.to_point(&snapshot) == newest_selection.start
428 } else {
429 range.end.to_point(&snapshot) == newest_selection.end
430 };
431 if focus_assist {
432 assist_to_focus = Some(assist_id);
433 }
434 }
435
436 let [prompt_block_id, end_block_id] =
437 self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
438
439 assists.push((
440 assist_id,
441 range,
442 prompt_editor,
443 prompt_block_id,
444 end_block_id,
445 ));
446 }
447
448 let editor_assists = self
449 .assists_by_editor
450 .entry(editor.downgrade())
451 .or_insert_with(|| EditorInlineAssists::new(&editor, window, cx));
452 let mut assist_group = InlineAssistGroup::new();
453 for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
454 let codegen = prompt_editor.read(cx).codegen().clone();
455
456 self.assists.insert(
457 assist_id,
458 InlineAssist::new(
459 assist_id,
460 assist_group_id,
461 editor,
462 &prompt_editor,
463 prompt_block_id,
464 end_block_id,
465 range,
466 codegen,
467 workspace.clone(),
468 window,
469 cx,
470 ),
471 );
472 assist_group.assist_ids.push(assist_id);
473 editor_assists.assist_ids.push(assist_id);
474 }
475 self.assist_groups.insert(assist_group_id, assist_group);
476
477 if let Some(assist_id) = assist_to_focus {
478 self.focus_assist(assist_id, window, cx);
479 }
480 }
481
482 #[allow(clippy::too_many_arguments)]
483 pub fn suggest_assist(
484 &mut self,
485 editor: &Entity<Editor>,
486 mut range: Range<Anchor>,
487 initial_prompt: String,
488 initial_transaction_id: Option<TransactionId>,
489 focus: bool,
490 workspace: WeakEntity<Workspace>,
491 thread_store: Option<WeakEntity<ThreadStore>>,
492 window: &mut Window,
493 cx: &mut App,
494 ) -> InlineAssistId {
495 let assist_group_id = self.next_assist_group_id.post_inc();
496 let prompt_buffer = cx.new(|cx| Buffer::local(&initial_prompt, cx));
497 let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
498
499 let assist_id = self.next_assist_id.post_inc();
500
501 let buffer = editor.read(cx).buffer().clone();
502 {
503 let snapshot = buffer.read(cx).read(cx);
504 range.start = range.start.bias_left(&snapshot);
505 range.end = range.end.bias_right(&snapshot);
506 }
507
508 let context_store = cx.new(|_cx| ContextStore::new(workspace.clone()));
509
510 let codegen = cx.new(|cx| {
511 BufferCodegen::new(
512 editor.read(cx).buffer().clone(),
513 range.clone(),
514 initial_transaction_id,
515 context_store.clone(),
516 self.telemetry.clone(),
517 self.prompt_builder.clone(),
518 cx,
519 )
520 });
521
522 let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
523 let prompt_editor = cx.new(|cx| {
524 PromptEditor::new_buffer(
525 assist_id,
526 gutter_dimensions.clone(),
527 self.prompt_history.clone(),
528 prompt_buffer.clone(),
529 codegen.clone(),
530 self.fs.clone(),
531 context_store,
532 workspace.clone(),
533 thread_store,
534 window,
535 cx,
536 )
537 });
538
539 let [prompt_block_id, end_block_id] =
540 self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
541
542 let editor_assists = self
543 .assists_by_editor
544 .entry(editor.downgrade())
545 .or_insert_with(|| EditorInlineAssists::new(&editor, window, cx));
546
547 let mut assist_group = InlineAssistGroup::new();
548 self.assists.insert(
549 assist_id,
550 InlineAssist::new(
551 assist_id,
552 assist_group_id,
553 editor,
554 &prompt_editor,
555 prompt_block_id,
556 end_block_id,
557 range,
558 codegen.clone(),
559 workspace.clone(),
560 window,
561 cx,
562 ),
563 );
564 assist_group.assist_ids.push(assist_id);
565 editor_assists.assist_ids.push(assist_id);
566 self.assist_groups.insert(assist_group_id, assist_group);
567
568 if focus {
569 self.focus_assist(assist_id, window, cx);
570 }
571
572 assist_id
573 }
574
575 fn insert_assist_blocks(
576 &self,
577 editor: &Entity<Editor>,
578 range: &Range<Anchor>,
579 prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
580 cx: &mut App,
581 ) -> [CustomBlockId; 2] {
582 let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
583 prompt_editor
584 .editor
585 .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
586 });
587 let assist_blocks = vec![
588 BlockProperties {
589 style: BlockStyle::Sticky,
590 placement: BlockPlacement::Above(range.start),
591 height: prompt_editor_height,
592 render: build_assist_editor_renderer(prompt_editor),
593 priority: 0,
594 },
595 BlockProperties {
596 style: BlockStyle::Sticky,
597 placement: BlockPlacement::Below(range.end),
598 height: 0,
599 render: Arc::new(|cx| {
600 v_flex()
601 .h_full()
602 .w_full()
603 .border_t_1()
604 .border_color(cx.theme().status().info_border)
605 .into_any_element()
606 }),
607 priority: 0,
608 },
609 ];
610
611 editor.update(cx, |editor, cx| {
612 let block_ids = editor.insert_blocks(assist_blocks, None, cx);
613 [block_ids[0], block_ids[1]]
614 })
615 }
616
617 fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
618 let assist = &self.assists[&assist_id];
619 let Some(decorations) = assist.decorations.as_ref() else {
620 return;
621 };
622 let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
623 let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
624
625 assist_group.active_assist_id = Some(assist_id);
626 if assist_group.linked {
627 for assist_id in &assist_group.assist_ids {
628 if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
629 decorations.prompt_editor.update(cx, |prompt_editor, cx| {
630 prompt_editor.set_show_cursor_when_unfocused(true, cx)
631 });
632 }
633 }
634 }
635
636 assist
637 .editor
638 .update(cx, |editor, cx| {
639 let scroll_top = editor.scroll_position(cx).y;
640 let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
641 let prompt_row = editor
642 .row_for_block(decorations.prompt_block_id, cx)
643 .unwrap()
644 .0 as f32;
645
646 if (scroll_top..scroll_bottom).contains(&prompt_row) {
647 editor_assists.scroll_lock = Some(InlineAssistScrollLock {
648 assist_id,
649 distance_from_top: prompt_row - scroll_top,
650 });
651 } else {
652 editor_assists.scroll_lock = None;
653 }
654 })
655 .ok();
656 }
657
658 fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
659 let assist = &self.assists[&assist_id];
660 let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
661 if assist_group.active_assist_id == Some(assist_id) {
662 assist_group.active_assist_id = None;
663 if assist_group.linked {
664 for assist_id in &assist_group.assist_ids {
665 if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
666 decorations.prompt_editor.update(cx, |prompt_editor, cx| {
667 prompt_editor.set_show_cursor_when_unfocused(false, cx)
668 });
669 }
670 }
671 }
672 }
673 }
674
675 fn handle_prompt_editor_event(
676 &mut self,
677 prompt_editor: Entity<PromptEditor<BufferCodegen>>,
678 event: &PromptEditorEvent,
679 window: &mut Window,
680 cx: &mut App,
681 ) {
682 let assist_id = prompt_editor.read(cx).id();
683 match event {
684 PromptEditorEvent::StartRequested => {
685 self.start_assist(assist_id, window, cx);
686 }
687 PromptEditorEvent::StopRequested => {
688 self.stop_assist(assist_id, cx);
689 }
690 PromptEditorEvent::ConfirmRequested { execute: _ } => {
691 self.finish_assist(assist_id, false, window, cx);
692 }
693 PromptEditorEvent::CancelRequested => {
694 self.finish_assist(assist_id, true, window, cx);
695 }
696 PromptEditorEvent::DismissRequested => {
697 self.dismiss_assist(assist_id, window, cx);
698 }
699 PromptEditorEvent::Resized { .. } => {
700 // This only matters for the terminal inline assistant
701 }
702 }
703 }
704
705 fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
706 let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
707 return;
708 };
709
710 if editor.read(cx).selections.count() == 1 {
711 let (selection, buffer) = editor.update(cx, |editor, cx| {
712 (
713 editor.selections.newest::<usize>(cx),
714 editor.buffer().read(cx).snapshot(cx),
715 )
716 });
717 for assist_id in &editor_assists.assist_ids {
718 let assist = &self.assists[assist_id];
719 let assist_range = assist.range.to_offset(&buffer);
720 if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
721 {
722 if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
723 self.dismiss_assist(*assist_id, window, cx);
724 } else {
725 self.finish_assist(*assist_id, false, window, cx);
726 }
727
728 return;
729 }
730 }
731 }
732
733 cx.propagate();
734 }
735
736 fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
737 let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
738 return;
739 };
740
741 if editor.read(cx).selections.count() == 1 {
742 let (selection, buffer) = editor.update(cx, |editor, cx| {
743 (
744 editor.selections.newest::<usize>(cx),
745 editor.buffer().read(cx).snapshot(cx),
746 )
747 });
748 let mut closest_assist_fallback = None;
749 for assist_id in &editor_assists.assist_ids {
750 let assist = &self.assists[assist_id];
751 let assist_range = assist.range.to_offset(&buffer);
752 if assist.decorations.is_some() {
753 if assist_range.contains(&selection.start)
754 && assist_range.contains(&selection.end)
755 {
756 self.focus_assist(*assist_id, window, cx);
757 return;
758 } else {
759 let distance_from_selection = assist_range
760 .start
761 .abs_diff(selection.start)
762 .min(assist_range.start.abs_diff(selection.end))
763 + assist_range
764 .end
765 .abs_diff(selection.start)
766 .min(assist_range.end.abs_diff(selection.end));
767 match closest_assist_fallback {
768 Some((_, old_distance)) => {
769 if distance_from_selection < old_distance {
770 closest_assist_fallback =
771 Some((assist_id, distance_from_selection));
772 }
773 }
774 None => {
775 closest_assist_fallback = Some((assist_id, distance_from_selection))
776 }
777 }
778 }
779 }
780 }
781
782 if let Some((&assist_id, _)) = closest_assist_fallback {
783 self.focus_assist(assist_id, window, cx);
784 }
785 }
786
787 cx.propagate();
788 }
789
790 fn handle_editor_release(
791 &mut self,
792 editor: WeakEntity<Editor>,
793 window: &mut Window,
794 cx: &mut App,
795 ) {
796 if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
797 for assist_id in editor_assists.assist_ids.clone() {
798 self.finish_assist(assist_id, true, window, cx);
799 }
800 }
801 }
802
803 fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
804 let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
805 return;
806 };
807 let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
808 return;
809 };
810 let assist = &self.assists[&scroll_lock.assist_id];
811 let Some(decorations) = assist.decorations.as_ref() else {
812 return;
813 };
814
815 editor.update(cx, |editor, cx| {
816 let scroll_position = editor.scroll_position(cx);
817 let target_scroll_top = editor
818 .row_for_block(decorations.prompt_block_id, cx)
819 .unwrap()
820 .0 as f32
821 - scroll_lock.distance_from_top;
822 if target_scroll_top != scroll_position.y {
823 editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
824 }
825 });
826 }
827
828 fn handle_editor_event(
829 &mut self,
830 editor: Entity<Editor>,
831 event: &EditorEvent,
832 window: &mut Window,
833 cx: &mut App,
834 ) {
835 let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
836 return;
837 };
838
839 match event {
840 EditorEvent::Edited { transaction_id } => {
841 let buffer = editor.read(cx).buffer().read(cx);
842 let edited_ranges =
843 buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
844 let snapshot = buffer.snapshot(cx);
845
846 for assist_id in editor_assists.assist_ids.clone() {
847 let assist = &self.assists[&assist_id];
848 if matches!(
849 assist.codegen.read(cx).status(cx),
850 CodegenStatus::Error(_) | CodegenStatus::Done
851 ) {
852 let assist_range = assist.range.to_offset(&snapshot);
853 if edited_ranges
854 .iter()
855 .any(|range| range.overlaps(&assist_range))
856 {
857 self.finish_assist(assist_id, false, window, cx);
858 }
859 }
860 }
861 }
862 EditorEvent::ScrollPositionChanged { .. } => {
863 if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
864 let assist = &self.assists[&scroll_lock.assist_id];
865 if let Some(decorations) = assist.decorations.as_ref() {
866 let distance_from_top = editor.update(cx, |editor, cx| {
867 let scroll_top = editor.scroll_position(cx).y;
868 let prompt_row = editor
869 .row_for_block(decorations.prompt_block_id, cx)
870 .unwrap()
871 .0 as f32;
872 prompt_row - scroll_top
873 });
874
875 if distance_from_top != scroll_lock.distance_from_top {
876 editor_assists.scroll_lock = None;
877 }
878 }
879 }
880 }
881 EditorEvent::SelectionsChanged { .. } => {
882 for assist_id in editor_assists.assist_ids.clone() {
883 let assist = &self.assists[&assist_id];
884 if let Some(decorations) = assist.decorations.as_ref() {
885 if decorations
886 .prompt_editor
887 .focus_handle(cx)
888 .is_focused(window)
889 {
890 return;
891 }
892 }
893 }
894
895 editor_assists.scroll_lock = None;
896 }
897 _ => {}
898 }
899 }
900
901 pub fn finish_assist(
902 &mut self,
903 assist_id: InlineAssistId,
904 undo: bool,
905 window: &mut Window,
906 cx: &mut App,
907 ) {
908 if let Some(assist) = self.assists.get(&assist_id) {
909 let assist_group_id = assist.group_id;
910 if self.assist_groups[&assist_group_id].linked {
911 for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
912 self.finish_assist(assist_id, undo, window, cx);
913 }
914 return;
915 }
916 }
917
918 self.dismiss_assist(assist_id, window, cx);
919
920 if let Some(assist) = self.assists.remove(&assist_id) {
921 if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
922 {
923 entry.get_mut().assist_ids.retain(|id| *id != assist_id);
924 if entry.get().assist_ids.is_empty() {
925 entry.remove();
926 }
927 }
928
929 if let hash_map::Entry::Occupied(mut entry) =
930 self.assists_by_editor.entry(assist.editor.clone())
931 {
932 entry.get_mut().assist_ids.retain(|id| *id != assist_id);
933 if entry.get().assist_ids.is_empty() {
934 entry.remove();
935 if let Some(editor) = assist.editor.upgrade() {
936 self.update_editor_highlights(&editor, cx);
937 }
938 } else {
939 entry.get().highlight_updates.send(()).ok();
940 }
941 }
942
943 let active_alternative = assist.codegen.read(cx).active_alternative().clone();
944 let message_id = active_alternative.read(cx).message_id.clone();
945
946 if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
947 let language_name = assist.editor.upgrade().and_then(|editor| {
948 let multibuffer = editor.read(cx).buffer().read(cx);
949 let snapshot = multibuffer.snapshot(cx);
950 let ranges = snapshot.range_to_buffer_ranges(assist.range.clone());
951 ranges
952 .first()
953 .and_then(|(buffer, _, _)| buffer.language())
954 .map(|language| language.name())
955 });
956 report_assistant_event(
957 AssistantEvent {
958 conversation_id: None,
959 kind: AssistantKind::Inline,
960 message_id,
961 phase: if undo {
962 AssistantPhase::Rejected
963 } else {
964 AssistantPhase::Accepted
965 },
966 model: model.telemetry_id(),
967 model_provider: model.provider_id().to_string(),
968 response_latency: None,
969 error_message: None,
970 language_name: language_name.map(|name| name.to_proto()),
971 },
972 Some(self.telemetry.clone()),
973 cx.http_client(),
974 model.api_key(cx),
975 cx.background_executor(),
976 );
977 }
978
979 if undo {
980 assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
981 } else {
982 self.confirmed_assists.insert(assist_id, active_alternative);
983 }
984 }
985 }
986
987 fn dismiss_assist(
988 &mut self,
989 assist_id: InlineAssistId,
990 window: &mut Window,
991 cx: &mut App,
992 ) -> bool {
993 let Some(assist) = self.assists.get_mut(&assist_id) else {
994 return false;
995 };
996 let Some(editor) = assist.editor.upgrade() else {
997 return false;
998 };
999 let Some(decorations) = assist.decorations.take() else {
1000 return false;
1001 };
1002
1003 editor.update(cx, |editor, cx| {
1004 let mut to_remove = decorations.removed_line_block_ids;
1005 to_remove.insert(decorations.prompt_block_id);
1006 to_remove.insert(decorations.end_block_id);
1007 editor.remove_blocks(to_remove, None, cx);
1008 });
1009
1010 if decorations
1011 .prompt_editor
1012 .focus_handle(cx)
1013 .contains_focused(window, cx)
1014 {
1015 self.focus_next_assist(assist_id, window, cx);
1016 }
1017
1018 if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1019 if editor_assists
1020 .scroll_lock
1021 .as_ref()
1022 .map_or(false, |lock| lock.assist_id == assist_id)
1023 {
1024 editor_assists.scroll_lock = None;
1025 }
1026 editor_assists.highlight_updates.send(()).ok();
1027 }
1028
1029 true
1030 }
1031
1032 fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1033 let Some(assist) = self.assists.get(&assist_id) else {
1034 return;
1035 };
1036
1037 let assist_group = &self.assist_groups[&assist.group_id];
1038 let assist_ix = assist_group
1039 .assist_ids
1040 .iter()
1041 .position(|id| *id == assist_id)
1042 .unwrap();
1043 let assist_ids = assist_group
1044 .assist_ids
1045 .iter()
1046 .skip(assist_ix + 1)
1047 .chain(assist_group.assist_ids.iter().take(assist_ix));
1048
1049 for assist_id in assist_ids {
1050 let assist = &self.assists[assist_id];
1051 if assist.decorations.is_some() {
1052 self.focus_assist(*assist_id, window, cx);
1053 return;
1054 }
1055 }
1056
1057 assist
1058 .editor
1059 .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
1060 .ok();
1061 }
1062
1063 fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1064 let Some(assist) = self.assists.get(&assist_id) else {
1065 return;
1066 };
1067
1068 if let Some(decorations) = assist.decorations.as_ref() {
1069 decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1070 prompt_editor.editor.update(cx, |editor, cx| {
1071 window.focus(&editor.focus_handle(cx));
1072 editor.select_all(&SelectAll, window, cx);
1073 })
1074 });
1075 }
1076
1077 self.scroll_to_assist(assist_id, window, cx);
1078 }
1079
1080 pub fn scroll_to_assist(
1081 &mut self,
1082 assist_id: InlineAssistId,
1083 window: &mut Window,
1084 cx: &mut App,
1085 ) {
1086 let Some(assist) = self.assists.get(&assist_id) else {
1087 return;
1088 };
1089 let Some(editor) = assist.editor.upgrade() else {
1090 return;
1091 };
1092
1093 let position = assist.range.start;
1094 editor.update(cx, |editor, cx| {
1095 editor.change_selections(None, window, cx, |selections| {
1096 selections.select_anchor_ranges([position..position])
1097 });
1098
1099 let mut scroll_target_top;
1100 let mut scroll_target_bottom;
1101 if let Some(decorations) = assist.decorations.as_ref() {
1102 scroll_target_top = editor
1103 .row_for_block(decorations.prompt_block_id, cx)
1104 .unwrap()
1105 .0 as f32;
1106 scroll_target_bottom = editor
1107 .row_for_block(decorations.end_block_id, cx)
1108 .unwrap()
1109 .0 as f32;
1110 } else {
1111 let snapshot = editor.snapshot(window, cx);
1112 let start_row = assist
1113 .range
1114 .start
1115 .to_display_point(&snapshot.display_snapshot)
1116 .row();
1117 scroll_target_top = start_row.0 as f32;
1118 scroll_target_bottom = scroll_target_top + 1.;
1119 }
1120 scroll_target_top -= editor.vertical_scroll_margin() as f32;
1121 scroll_target_bottom += editor.vertical_scroll_margin() as f32;
1122
1123 let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1124 let scroll_top = editor.scroll_position(cx).y;
1125 let scroll_bottom = scroll_top + height_in_lines;
1126
1127 if scroll_target_top < scroll_top {
1128 editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1129 } else if scroll_target_bottom > scroll_bottom {
1130 if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1131 editor.set_scroll_position(
1132 point(0., scroll_target_bottom - height_in_lines),
1133 window,
1134 cx,
1135 );
1136 } else {
1137 editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1138 }
1139 }
1140 });
1141 }
1142
1143 fn unlink_assist_group(
1144 &mut self,
1145 assist_group_id: InlineAssistGroupId,
1146 window: &mut Window,
1147 cx: &mut App,
1148 ) -> Vec<InlineAssistId> {
1149 let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1150 assist_group.linked = false;
1151 for assist_id in &assist_group.assist_ids {
1152 let assist = self.assists.get_mut(assist_id).unwrap();
1153 if let Some(editor_decorations) = assist.decorations.as_ref() {
1154 editor_decorations
1155 .prompt_editor
1156 .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1157 }
1158 }
1159 assist_group.assist_ids.clone()
1160 }
1161
1162 pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1163 let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1164 assist
1165 } else {
1166 return;
1167 };
1168
1169 let assist_group_id = assist.group_id;
1170 if self.assist_groups[&assist_group_id].linked {
1171 for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1172 self.start_assist(assist_id, window, cx);
1173 }
1174 return;
1175 }
1176
1177 let Some(user_prompt) = assist.user_prompt(cx) else {
1178 return;
1179 };
1180
1181 self.prompt_history.retain(|prompt| *prompt != user_prompt);
1182 self.prompt_history.push_back(user_prompt.clone());
1183 if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1184 self.prompt_history.pop_front();
1185 }
1186
1187 assist
1188 .codegen
1189 .update(cx, |codegen, cx| codegen.start(user_prompt, cx))
1190 .log_err();
1191 }
1192
1193 pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1194 let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1195 assist
1196 } else {
1197 return;
1198 };
1199
1200 assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1201 }
1202
1203 fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1204 let mut gutter_pending_ranges = Vec::new();
1205 let mut gutter_transformed_ranges = Vec::new();
1206 let mut foreground_ranges = Vec::new();
1207 let mut inserted_row_ranges = Vec::new();
1208 let empty_assist_ids = Vec::new();
1209 let assist_ids = self
1210 .assists_by_editor
1211 .get(&editor.downgrade())
1212 .map_or(&empty_assist_ids, |editor_assists| {
1213 &editor_assists.assist_ids
1214 });
1215
1216 for assist_id in assist_ids {
1217 if let Some(assist) = self.assists.get(assist_id) {
1218 let codegen = assist.codegen.read(cx);
1219 let buffer = codegen.buffer(cx).read(cx).read(cx);
1220 foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1221
1222 let pending_range =
1223 codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1224 if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1225 gutter_pending_ranges.push(pending_range);
1226 }
1227
1228 if let Some(edit_position) = codegen.edit_position(cx) {
1229 let edited_range = assist.range.start..edit_position;
1230 if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1231 gutter_transformed_ranges.push(edited_range);
1232 }
1233 }
1234
1235 if assist.decorations.is_some() {
1236 inserted_row_ranges
1237 .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1238 }
1239 }
1240 }
1241
1242 let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1243 merge_ranges(&mut foreground_ranges, &snapshot);
1244 merge_ranges(&mut gutter_pending_ranges, &snapshot);
1245 merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1246 editor.update(cx, |editor, cx| {
1247 enum GutterPendingRange {}
1248 if gutter_pending_ranges.is_empty() {
1249 editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1250 } else {
1251 editor.highlight_gutter::<GutterPendingRange>(
1252 &gutter_pending_ranges,
1253 |cx| cx.theme().status().info_background,
1254 cx,
1255 )
1256 }
1257
1258 enum GutterTransformedRange {}
1259 if gutter_transformed_ranges.is_empty() {
1260 editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1261 } else {
1262 editor.highlight_gutter::<GutterTransformedRange>(
1263 &gutter_transformed_ranges,
1264 |cx| cx.theme().status().info,
1265 cx,
1266 )
1267 }
1268
1269 if foreground_ranges.is_empty() {
1270 editor.clear_highlights::<InlineAssist>(cx);
1271 } else {
1272 editor.highlight_text::<InlineAssist>(
1273 foreground_ranges,
1274 HighlightStyle {
1275 fade_out: Some(0.6),
1276 ..Default::default()
1277 },
1278 cx,
1279 );
1280 }
1281
1282 editor.clear_row_highlights::<InlineAssist>();
1283 for row_range in inserted_row_ranges {
1284 editor.highlight_rows::<InlineAssist>(
1285 row_range,
1286 cx.theme().status().info_background,
1287 false,
1288 cx,
1289 );
1290 }
1291 });
1292 }
1293
1294 fn update_editor_blocks(
1295 &mut self,
1296 editor: &Entity<Editor>,
1297 assist_id: InlineAssistId,
1298 window: &mut Window,
1299 cx: &mut App,
1300 ) {
1301 let Some(assist) = self.assists.get_mut(&assist_id) else {
1302 return;
1303 };
1304 let Some(decorations) = assist.decorations.as_mut() else {
1305 return;
1306 };
1307
1308 let codegen = assist.codegen.read(cx);
1309 let old_snapshot = codegen.snapshot(cx);
1310 let old_buffer = codegen.old_buffer(cx);
1311 let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1312
1313 editor.update(cx, |editor, cx| {
1314 let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1315 editor.remove_blocks(old_blocks, None, cx);
1316
1317 let mut new_blocks = Vec::new();
1318 for (new_row, old_row_range) in deleted_row_ranges {
1319 let (_, buffer_start) = old_snapshot
1320 .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1321 .unwrap();
1322 let (_, buffer_end) = old_snapshot
1323 .point_to_buffer_offset(Point::new(
1324 *old_row_range.end(),
1325 old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1326 ))
1327 .unwrap();
1328
1329 let deleted_lines_editor = cx.new(|cx| {
1330 let multi_buffer =
1331 cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1332 multi_buffer.update(cx, |multi_buffer, cx| {
1333 multi_buffer.push_excerpts(
1334 old_buffer.clone(),
1335 Some(ExcerptRange {
1336 context: buffer_start..buffer_end,
1337 primary: None,
1338 }),
1339 cx,
1340 );
1341 });
1342
1343 enum DeletedLines {}
1344 let mut editor = Editor::for_multibuffer(multi_buffer, None, true, window, cx);
1345 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1346 editor.set_show_wrap_guides(false, cx);
1347 editor.set_show_gutter(false, cx);
1348 editor.scroll_manager.set_forbid_vertical_scroll(true);
1349 editor.set_show_scrollbars(false, cx);
1350 editor.set_read_only(true);
1351 editor.set_show_edit_predictions(Some(false), window, cx);
1352 editor.highlight_rows::<DeletedLines>(
1353 Anchor::min()..Anchor::max(),
1354 cx.theme().status().deleted_background,
1355 false,
1356 cx,
1357 );
1358 editor
1359 });
1360
1361 let height =
1362 deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1363 new_blocks.push(BlockProperties {
1364 placement: BlockPlacement::Above(new_row),
1365 height,
1366 style: BlockStyle::Flex,
1367 render: Arc::new(move |cx| {
1368 div()
1369 .block_mouse_down()
1370 .bg(cx.theme().status().deleted_background)
1371 .size_full()
1372 .h(height as f32 * cx.window.line_height())
1373 .pl(cx.gutter_dimensions.full_width())
1374 .child(deleted_lines_editor.clone())
1375 .into_any_element()
1376 }),
1377 priority: 0,
1378 });
1379 }
1380
1381 decorations.removed_line_block_ids = editor
1382 .insert_blocks(new_blocks, None, cx)
1383 .into_iter()
1384 .collect();
1385 })
1386 }
1387
1388 fn resolve_inline_assist_target(
1389 workspace: &mut Workspace,
1390 assistant_panel: Option<Entity<AssistantPanel>>,
1391 window: &mut Window,
1392 cx: &mut App,
1393 ) -> Option<InlineAssistTarget> {
1394 if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx) {
1395 if terminal_panel
1396 .read(cx)
1397 .focus_handle(cx)
1398 .contains_focused(window, cx)
1399 {
1400 if let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1401 pane.read(cx)
1402 .active_item()
1403 .and_then(|t| t.downcast::<TerminalView>())
1404 }) {
1405 return Some(InlineAssistTarget::Terminal(terminal_view));
1406 }
1407 }
1408 }
1409
1410 let context_editor = assistant_panel
1411 .and_then(|panel| panel.read(cx).active_context_editor())
1412 .and_then(|editor| {
1413 let editor = &editor.read(cx).editor().clone();
1414 if editor.read(cx).is_focused(window) {
1415 Some(editor.clone())
1416 } else {
1417 None
1418 }
1419 });
1420
1421 if let Some(context_editor) = context_editor {
1422 Some(InlineAssistTarget::Editor(context_editor))
1423 } else if let Some(workspace_editor) = workspace
1424 .active_item(cx)
1425 .and_then(|item| item.act_as::<Editor>(cx))
1426 {
1427 Some(InlineAssistTarget::Editor(workspace_editor))
1428 } else if let Some(terminal_view) = workspace
1429 .active_item(cx)
1430 .and_then(|item| item.act_as::<TerminalView>(cx))
1431 {
1432 Some(InlineAssistTarget::Terminal(terminal_view))
1433 } else {
1434 None
1435 }
1436 }
1437}
1438
1439struct EditorInlineAssists {
1440 assist_ids: Vec<InlineAssistId>,
1441 scroll_lock: Option<InlineAssistScrollLock>,
1442 highlight_updates: async_watch::Sender<()>,
1443 _update_highlights: Task<Result<()>>,
1444 _subscriptions: Vec<gpui::Subscription>,
1445}
1446
1447struct InlineAssistScrollLock {
1448 assist_id: InlineAssistId,
1449 distance_from_top: f32,
1450}
1451
1452impl EditorInlineAssists {
1453 #[allow(clippy::too_many_arguments)]
1454 fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1455 let (highlight_updates_tx, mut highlight_updates_rx) = async_watch::channel(());
1456 Self {
1457 assist_ids: Vec::new(),
1458 scroll_lock: None,
1459 highlight_updates: highlight_updates_tx,
1460 _update_highlights: cx.spawn(|cx| {
1461 let editor = editor.downgrade();
1462 async move {
1463 while let Ok(()) = highlight_updates_rx.changed().await {
1464 let editor = editor.upgrade().context("editor was dropped")?;
1465 cx.update_global(|assistant: &mut InlineAssistant, cx| {
1466 assistant.update_editor_highlights(&editor, cx);
1467 })?;
1468 }
1469 Ok(())
1470 }
1471 }),
1472 _subscriptions: vec![
1473 cx.observe_release_in(editor, window, {
1474 let editor = editor.downgrade();
1475 |_, window, cx| {
1476 InlineAssistant::update_global(cx, |this, cx| {
1477 this.handle_editor_release(editor, window, cx);
1478 })
1479 }
1480 }),
1481 window.observe(editor, cx, move |editor, window, cx| {
1482 InlineAssistant::update_global(cx, |this, cx| {
1483 this.handle_editor_change(editor, window, cx)
1484 })
1485 }),
1486 window.subscribe(editor, cx, move |editor, event, window, cx| {
1487 InlineAssistant::update_global(cx, |this, cx| {
1488 this.handle_editor_event(editor, event, window, cx)
1489 })
1490 }),
1491 editor.update(cx, |editor, cx| {
1492 let editor_handle = cx.entity().downgrade();
1493 editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1494 InlineAssistant::update_global(cx, |this, cx| {
1495 if let Some(editor) = editor_handle.upgrade() {
1496 this.handle_editor_newline(editor, window, cx)
1497 }
1498 })
1499 })
1500 }),
1501 editor.update(cx, |editor, cx| {
1502 let editor_handle = cx.entity().downgrade();
1503 editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1504 InlineAssistant::update_global(cx, |this, cx| {
1505 if let Some(editor) = editor_handle.upgrade() {
1506 this.handle_editor_cancel(editor, window, cx)
1507 }
1508 })
1509 })
1510 }),
1511 ],
1512 }
1513 }
1514}
1515
1516struct InlineAssistGroup {
1517 assist_ids: Vec<InlineAssistId>,
1518 linked: bool,
1519 active_assist_id: Option<InlineAssistId>,
1520}
1521
1522impl InlineAssistGroup {
1523 fn new() -> Self {
1524 Self {
1525 assist_ids: Vec::new(),
1526 linked: true,
1527 active_assist_id: None,
1528 }
1529 }
1530}
1531
1532fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1533 let editor = editor.clone();
1534
1535 Arc::new(move |cx: &mut BlockContext| {
1536 let gutter_dimensions = editor.read(cx).gutter_dimensions();
1537
1538 *gutter_dimensions.lock() = *cx.gutter_dimensions;
1539 editor.clone().into_any_element()
1540 })
1541}
1542
1543#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1544struct InlineAssistGroupId(usize);
1545
1546impl InlineAssistGroupId {
1547 fn post_inc(&mut self) -> InlineAssistGroupId {
1548 let id = *self;
1549 self.0 += 1;
1550 id
1551 }
1552}
1553
1554pub struct InlineAssist {
1555 group_id: InlineAssistGroupId,
1556 range: Range<Anchor>,
1557 editor: WeakEntity<Editor>,
1558 decorations: Option<InlineAssistDecorations>,
1559 codegen: Entity<BufferCodegen>,
1560 _subscriptions: Vec<Subscription>,
1561 workspace: WeakEntity<Workspace>,
1562}
1563
1564impl InlineAssist {
1565 #[allow(clippy::too_many_arguments)]
1566 fn new(
1567 assist_id: InlineAssistId,
1568 group_id: InlineAssistGroupId,
1569 editor: &Entity<Editor>,
1570 prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1571 prompt_block_id: CustomBlockId,
1572 end_block_id: CustomBlockId,
1573 range: Range<Anchor>,
1574 codegen: Entity<BufferCodegen>,
1575 workspace: WeakEntity<Workspace>,
1576 window: &mut Window,
1577 cx: &mut App,
1578 ) -> Self {
1579 let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1580 InlineAssist {
1581 group_id,
1582 editor: editor.downgrade(),
1583 decorations: Some(InlineAssistDecorations {
1584 prompt_block_id,
1585 prompt_editor: prompt_editor.clone(),
1586 removed_line_block_ids: HashSet::default(),
1587 end_block_id,
1588 }),
1589 range,
1590 codegen: codegen.clone(),
1591 workspace: workspace.clone(),
1592 _subscriptions: vec![
1593 window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1594 InlineAssistant::update_global(cx, |this, cx| {
1595 this.handle_prompt_editor_focus_in(assist_id, cx)
1596 })
1597 }),
1598 window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1599 InlineAssistant::update_global(cx, |this, cx| {
1600 this.handle_prompt_editor_focus_out(assist_id, cx)
1601 })
1602 }),
1603 window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1604 InlineAssistant::update_global(cx, |this, cx| {
1605 this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1606 })
1607 }),
1608 window.observe(&codegen, cx, {
1609 let editor = editor.downgrade();
1610 move |_, window, cx| {
1611 if let Some(editor) = editor.upgrade() {
1612 InlineAssistant::update_global(cx, |this, cx| {
1613 if let Some(editor_assists) =
1614 this.assists_by_editor.get(&editor.downgrade())
1615 {
1616 editor_assists.highlight_updates.send(()).ok();
1617 }
1618
1619 this.update_editor_blocks(&editor, assist_id, window, cx);
1620 })
1621 }
1622 }
1623 }),
1624 window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1625 InlineAssistant::update_global(cx, |this, cx| match event {
1626 CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1627 CodegenEvent::Finished => {
1628 let assist = if let Some(assist) = this.assists.get(&assist_id) {
1629 assist
1630 } else {
1631 return;
1632 };
1633
1634 if let CodegenStatus::Error(error) = codegen.read(cx).status(cx) {
1635 if assist.decorations.is_none() {
1636 if let Some(workspace) = assist.workspace.upgrade() {
1637 let error = format!("Inline assistant error: {}", error);
1638 workspace.update(cx, |workspace, cx| {
1639 struct InlineAssistantError;
1640
1641 let id =
1642 NotificationId::composite::<InlineAssistantError>(
1643 assist_id.0,
1644 );
1645
1646 workspace.show_toast(Toast::new(id, error), cx);
1647 })
1648 }
1649 }
1650 }
1651
1652 if assist.decorations.is_none() {
1653 this.finish_assist(assist_id, false, window, cx);
1654 }
1655 }
1656 })
1657 }),
1658 ],
1659 }
1660 }
1661
1662 fn user_prompt(&self, cx: &App) -> Option<String> {
1663 let decorations = self.decorations.as_ref()?;
1664 Some(decorations.prompt_editor.read(cx).prompt(cx))
1665 }
1666}
1667
1668struct InlineAssistDecorations {
1669 prompt_block_id: CustomBlockId,
1670 prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1671 removed_line_block_ids: HashSet<CustomBlockId>,
1672 end_block_id: CustomBlockId,
1673}
1674
1675struct AssistantCodeActionProvider {
1676 editor: WeakEntity<Editor>,
1677 workspace: WeakEntity<Workspace>,
1678 thread_store: Option<WeakEntity<ThreadStore>>,
1679}
1680
1681const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant2";
1682
1683impl CodeActionProvider for AssistantCodeActionProvider {
1684 fn id(&self) -> Arc<str> {
1685 ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1686 }
1687
1688 fn code_actions(
1689 &self,
1690 buffer: &Entity<Buffer>,
1691 range: Range<text::Anchor>,
1692 _: &mut Window,
1693 cx: &mut App,
1694 ) -> Task<Result<Vec<CodeAction>>> {
1695 if !AssistantSettings::get_global(cx).enabled {
1696 return Task::ready(Ok(Vec::new()));
1697 }
1698
1699 let snapshot = buffer.read(cx).snapshot();
1700 let mut range = range.to_point(&snapshot);
1701
1702 // Expand the range to line boundaries.
1703 range.start.column = 0;
1704 range.end.column = snapshot.line_len(range.end.row);
1705
1706 let mut has_diagnostics = false;
1707 for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1708 range.start = cmp::min(range.start, diagnostic.range.start);
1709 range.end = cmp::max(range.end, diagnostic.range.end);
1710 has_diagnostics = true;
1711 }
1712 if has_diagnostics {
1713 if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
1714 if let Some(symbol) = symbols_containing_start.last() {
1715 range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1716 range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1717 }
1718 }
1719
1720 if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
1721 if let Some(symbol) = symbols_containing_end.last() {
1722 range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1723 range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1724 }
1725 }
1726
1727 Task::ready(Ok(vec![CodeAction {
1728 server_id: language::LanguageServerId(0),
1729 range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1730 lsp_action: lsp::CodeAction {
1731 title: "Fix with Assistant".into(),
1732 ..Default::default()
1733 },
1734 }]))
1735 } else {
1736 Task::ready(Ok(Vec::new()))
1737 }
1738 }
1739
1740 fn apply_code_action(
1741 &self,
1742 buffer: Entity<Buffer>,
1743 action: CodeAction,
1744 excerpt_id: ExcerptId,
1745 _push_to_history: bool,
1746 window: &mut Window,
1747 cx: &mut App,
1748 ) -> Task<Result<ProjectTransaction>> {
1749 let editor = self.editor.clone();
1750 let workspace = self.workspace.clone();
1751 let thread_store = self.thread_store.clone();
1752 window.spawn(cx, |mut cx| async move {
1753 let editor = editor.upgrade().context("editor was released")?;
1754 let range = editor
1755 .update(&mut cx, |editor, cx| {
1756 editor.buffer().update(cx, |multibuffer, cx| {
1757 let buffer = buffer.read(cx);
1758 let multibuffer_snapshot = multibuffer.read(cx);
1759
1760 let old_context_range =
1761 multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1762 let mut new_context_range = old_context_range.clone();
1763 if action
1764 .range
1765 .start
1766 .cmp(&old_context_range.start, buffer)
1767 .is_lt()
1768 {
1769 new_context_range.start = action.range.start;
1770 }
1771 if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1772 new_context_range.end = action.range.end;
1773 }
1774 drop(multibuffer_snapshot);
1775
1776 if new_context_range != old_context_range {
1777 multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1778 }
1779
1780 let multibuffer_snapshot = multibuffer.read(cx);
1781 Some(
1782 multibuffer_snapshot
1783 .anchor_in_excerpt(excerpt_id, action.range.start)?
1784 ..multibuffer_snapshot
1785 .anchor_in_excerpt(excerpt_id, action.range.end)?,
1786 )
1787 })
1788 })?
1789 .context("invalid range")?;
1790
1791 cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
1792 let assist_id = assistant.suggest_assist(
1793 &editor,
1794 range,
1795 "Fix Diagnostics".into(),
1796 None,
1797 true,
1798 workspace,
1799 thread_store,
1800 window,
1801 cx,
1802 );
1803 assistant.start_assist(assist_id, window, cx);
1804 })?;
1805
1806 Ok(ProjectTransaction::default())
1807 })
1808 }
1809}
1810
1811fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
1812 ranges.sort_unstable_by(|a, b| {
1813 a.start
1814 .cmp(&b.start, buffer)
1815 .then_with(|| b.end.cmp(&a.end, buffer))
1816 });
1817
1818 let mut ix = 0;
1819 while ix + 1 < ranges.len() {
1820 let b = ranges[ix + 1].clone();
1821 let a = &mut ranges[ix];
1822 if a.end.cmp(&b.start, buffer).is_gt() {
1823 if a.end.cmp(&b.end, buffer).is_lt() {
1824 a.end = b.end;
1825 }
1826 ranges.remove(ix + 1);
1827 } else {
1828 ix += 1;
1829 }
1830 }
1831}