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