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