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