1use language_model::AnthropicEventData;
2use language_model::report_anthropic_event;
3use std::cmp;
4use std::mem;
5use std::ops::Range;
6use std::rc::Rc;
7use std::sync::Arc;
8use uuid::Uuid;
9
10use crate::ThreadHistory;
11use crate::context::load_context;
12use crate::mention_set::MentionSet;
13use crate::{
14 AgentPanel,
15 buffer_codegen::{BufferCodegen, CodegenAlternative, CodegenEvent},
16 inline_prompt_editor::{CodegenStatus, InlineAssistId, PromptEditor, PromptEditorEvent},
17 terminal_inline_assistant::TerminalInlineAssistant,
18};
19use agent::ThreadStore;
20use agent_settings::AgentSettings;
21use anyhow::{Context as _, Result};
22use collections::{HashMap, HashSet, VecDeque, hash_map};
23use editor::EditorSnapshot;
24use editor::MultiBufferOffset;
25use editor::RowExt;
26use editor::SelectionEffects;
27use editor::scroll::ScrollOffset;
28use editor::{
29 Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorEvent, ExcerptId, HighlightKey,
30 MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint,
31 actions::SelectAll,
32 display_map::{
33 BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, EditorMargins,
34 RenderBlock, ToDisplayPoint,
35 },
36};
37use fs::Fs;
38use futures::{FutureExt, channel::mpsc};
39use gpui::{
40 App, Context, Entity, Focusable, Global, HighlightStyle, Subscription, Task, UpdateGlobal,
41 WeakEntity, Window, point,
42};
43use language::{Buffer, Point, Selection, TransactionId};
44use language_model::{ConfigurationError, ConfiguredModel, LanguageModelRegistry};
45use multi_buffer::MultiBufferRow;
46use parking_lot::Mutex;
47use project::{CodeAction, DisableAiSettings, LspAction, Project, ProjectTransaction};
48use prompt_store::{PromptBuilder, PromptStore};
49use settings::{Settings, SettingsStore};
50
51use terminal_view::{TerminalView, terminal_panel::TerminalPanel};
52use text::{OffsetRangeExt, ToPoint as _};
53use ui::prelude::*;
54use util::{RangeExt, ResultExt, maybe};
55use workspace::{ItemHandle, Toast, Workspace, dock::Panel, notifications::NotificationId};
56use zed_actions::agent::OpenSettings;
57
58pub fn init(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>, cx: &mut App) {
59 cx.set_global(InlineAssistant::new(fs, prompt_builder));
60
61 cx.observe_global::<SettingsStore>(|cx| {
62 if DisableAiSettings::get_global(cx).disable_ai {
63 // Hide any active inline assist UI when AI is disabled
64 InlineAssistant::update_global(cx, |assistant, cx| {
65 assistant.cancel_all_active_completions(cx);
66 });
67 }
68 })
69 .detach();
70
71 cx.observe_new(|_workspace: &mut Workspace, window, cx| {
72 let Some(window) = window else {
73 return;
74 };
75 let workspace = cx.entity();
76 InlineAssistant::update_global(cx, |inline_assistant, cx| {
77 inline_assistant.register_workspace(&workspace, window, cx)
78 });
79 })
80 .detach();
81}
82
83const PROMPT_HISTORY_MAX_LEN: usize = 20;
84
85enum InlineAssistTarget {
86 Editor(Entity<Editor>),
87 Terminal(Entity<TerminalView>),
88}
89
90pub struct InlineAssistant {
91 next_assist_id: InlineAssistId,
92 next_assist_group_id: InlineAssistGroupId,
93 assists: HashMap<InlineAssistId, InlineAssist>,
94 assists_by_editor: HashMap<WeakEntity<Editor>, EditorInlineAssists>,
95 assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,
96 confirmed_assists: HashMap<InlineAssistId, Entity<CodegenAlternative>>,
97 prompt_history: VecDeque<String>,
98 prompt_builder: Arc<PromptBuilder>,
99 fs: Arc<dyn Fs>,
100 _inline_assistant_completions: Option<mpsc::UnboundedSender<anyhow::Result<InlineAssistId>>>,
101}
102
103impl Global for InlineAssistant {}
104
105impl InlineAssistant {
106 pub fn new(fs: Arc<dyn Fs>, prompt_builder: Arc<PromptBuilder>) -> Self {
107 Self {
108 next_assist_id: InlineAssistId::default(),
109 next_assist_group_id: InlineAssistGroupId::default(),
110 assists: HashMap::default(),
111 assists_by_editor: HashMap::default(),
112 assist_groups: HashMap::default(),
113 confirmed_assists: HashMap::default(),
114 prompt_history: VecDeque::default(),
115 prompt_builder,
116 fs,
117 _inline_assistant_completions: None,
118 }
119 }
120
121 pub fn register_workspace(
122 &mut self,
123 workspace: &Entity<Workspace>,
124 window: &mut Window,
125 cx: &mut App,
126 ) {
127 window
128 .subscribe(workspace, cx, |workspace, event, window, cx| {
129 Self::update_global(cx, |this, cx| {
130 this.handle_workspace_event(workspace, event, window, cx)
131 });
132 })
133 .detach();
134
135 let workspace_weak = workspace.downgrade();
136 cx.observe_global::<SettingsStore>(move |cx| {
137 let Some(workspace) = workspace_weak.upgrade() else {
138 return;
139 };
140 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
141 return;
142 };
143 let enabled = AgentSettings::get_global(cx).enabled(cx);
144 terminal_panel.update(cx, |terminal_panel, cx| {
145 terminal_panel.set_assistant_enabled(enabled, cx)
146 });
147 })
148 .detach();
149
150 cx.observe(workspace, |workspace, cx| {
151 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
152 return;
153 };
154 let enabled = AgentSettings::get_global(cx).enabled(cx);
155 if terminal_panel.read(cx).assistant_enabled() != enabled {
156 terminal_panel.update(cx, |terminal_panel, cx| {
157 terminal_panel.set_assistant_enabled(enabled, cx)
158 });
159 }
160 })
161 .detach();
162 }
163
164 /// Hides all active inline assists when AI is disabled
165 pub fn cancel_all_active_completions(&mut self, cx: &mut App) {
166 // Cancel all active completions in editors
167 for (editor_handle, _) in self.assists_by_editor.iter() {
168 if let Some(editor) = editor_handle.upgrade() {
169 let windows = cx.windows();
170 if !windows.is_empty() {
171 let window = windows[0];
172 let _ = window.update(cx, |_, window, cx| {
173 editor.update(cx, |editor, cx| {
174 if editor.has_active_edit_prediction() {
175 editor.cancel(&Default::default(), window, cx);
176 }
177 });
178 });
179 }
180 }
181 }
182 }
183
184 fn handle_workspace_event(
185 &mut self,
186 workspace: Entity<Workspace>,
187 event: &workspace::Event,
188 window: &mut Window,
189 cx: &mut App,
190 ) {
191 match event {
192 workspace::Event::UserSavedItem { item, .. } => {
193 // When the user manually saves an editor, automatically accepts all finished transformations.
194 if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx))
195 && let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade())
196 {
197 for assist_id in editor_assists.assist_ids.clone() {
198 let assist = &self.assists[&assist_id];
199 if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
200 self.finish_assist(assist_id, false, window, cx)
201 }
202 }
203 }
204 }
205 workspace::Event::ItemAdded { item } => {
206 self.register_workspace_item(&workspace, item.as_ref(), window, cx);
207 }
208 _ => (),
209 }
210 }
211
212 fn register_workspace_item(
213 &mut self,
214 workspace: &Entity<Workspace>,
215 item: &dyn ItemHandle,
216 window: &mut Window,
217 cx: &mut App,
218 ) {
219 let is_ai_enabled = !DisableAiSettings::get_global(cx).disable_ai;
220
221 if let Some(editor) = item.act_as::<Editor>(cx) {
222 editor.update(cx, |editor, cx| {
223 if is_ai_enabled {
224 editor.add_code_action_provider(
225 Rc::new(AssistantCodeActionProvider {
226 editor: cx.entity().downgrade(),
227 workspace: workspace.downgrade(),
228 }),
229 window,
230 cx,
231 );
232
233 if DisableAiSettings::get_global(cx).disable_ai {
234 // Cancel any active edit predictions
235 if editor.has_active_edit_prediction() {
236 editor.cancel(&Default::default(), window, cx);
237 }
238 }
239 } else {
240 editor.remove_code_action_provider(
241 ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
242 window,
243 cx,
244 );
245 }
246 });
247 }
248 }
249
250 pub fn inline_assist(
251 workspace: &mut Workspace,
252 action: &zed_actions::assistant::InlineAssist,
253 window: &mut Window,
254 cx: &mut Context<Workspace>,
255 ) {
256 if !AgentSettings::get_global(cx).enabled(cx) {
257 return;
258 }
259
260 let Some(inline_assist_target) = Self::resolve_inline_assist_target(workspace, window, cx)
261 else {
262 return;
263 };
264
265 let configuration_error = |cx| {
266 let model_registry = LanguageModelRegistry::read_global(cx);
267 model_registry.configuration_error(model_registry.inline_assistant_model(), cx)
268 };
269
270 let Some(agent_panel) = workspace.panel::<AgentPanel>(cx) else {
271 return;
272 };
273 let agent_panel = agent_panel.read(cx);
274
275 let prompt_store = agent_panel.prompt_store().as_ref().cloned();
276 let thread_store = agent_panel.thread_store().clone();
277 let history = agent_panel
278 .connection_store()
279 .read(cx)
280 .entry(&crate::Agent::NativeAgent)
281 .and_then(|s| s.read(cx).history().cloned());
282
283 let handle_assist =
284 |window: &mut Window, cx: &mut Context<Workspace>| match inline_assist_target {
285 InlineAssistTarget::Editor(active_editor) => {
286 InlineAssistant::update_global(cx, |assistant, cx| {
287 assistant.assist(
288 &active_editor,
289 cx.entity().downgrade(),
290 workspace.project().downgrade(),
291 thread_store,
292 prompt_store,
293 history.as_ref().map(|h| h.downgrade()),
294 action.prompt.clone(),
295 window,
296 cx,
297 );
298 })
299 }
300 InlineAssistTarget::Terminal(active_terminal) => {
301 TerminalInlineAssistant::update_global(cx, |assistant, cx| {
302 assistant.assist(
303 &active_terminal,
304 cx.entity().downgrade(),
305 workspace.project().downgrade(),
306 thread_store,
307 prompt_store,
308 history.as_ref().map(|h| h.downgrade()),
309 action.prompt.clone(),
310 window,
311 cx,
312 );
313 });
314 }
315 };
316
317 if let Some(error) = configuration_error(cx) {
318 if let ConfigurationError::ProviderNotAuthenticated(provider) = error {
319 cx.spawn(async move |_, cx| {
320 cx.update(|cx| provider.authenticate(cx)).await?;
321 anyhow::Ok(())
322 })
323 .detach_and_log_err(cx);
324
325 if configuration_error(cx).is_none() {
326 handle_assist(window, cx);
327 }
328 } else {
329 cx.spawn_in(window, async move |_, cx| {
330 let answer = cx
331 .prompt(
332 gpui::PromptLevel::Warning,
333 &error.to_string(),
334 None,
335 &["Configure", "Cancel"],
336 )
337 .await
338 .ok();
339 if let Some(answer) = answer
340 && answer == 0
341 {
342 cx.update(|window, cx| window.dispatch_action(Box::new(OpenSettings), cx))
343 .ok();
344 }
345 anyhow::Ok(())
346 })
347 .detach_and_log_err(cx);
348 }
349 } else {
350 handle_assist(window, cx);
351 }
352 }
353
354 fn codegen_ranges(
355 &mut self,
356 editor: &Entity<Editor>,
357 snapshot: &EditorSnapshot,
358 window: &mut Window,
359 cx: &mut App,
360 ) -> Option<(Vec<Range<Anchor>>, Selection<Point>)> {
361 let (initial_selections, newest_selection) = editor.update(cx, |editor, _| {
362 (
363 editor.selections.all::<Point>(&snapshot.display_snapshot),
364 editor
365 .selections
366 .newest::<Point>(&snapshot.display_snapshot),
367 )
368 });
369
370 // Check if there is already an inline assistant that contains the
371 // newest selection, if there is, focus it
372 if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
373 for assist_id in &editor_assists.assist_ids {
374 let assist = &self.assists[assist_id];
375 let range = assist.range.to_point(&snapshot.buffer_snapshot());
376 if range.start.row <= newest_selection.start.row
377 && newest_selection.end.row <= range.end.row
378 {
379 self.focus_assist(*assist_id, window, cx);
380 return None;
381 }
382 }
383 }
384
385 let mut selections = Vec::<Selection<Point>>::new();
386 let mut newest_selection = None;
387 for mut selection in initial_selections {
388 if selection.end == selection.start
389 && let Some(fold) =
390 snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
391 {
392 selection.start = fold.range().start;
393 selection.end = fold.range().end;
394 if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot().max_row() {
395 let chars = snapshot
396 .buffer_snapshot()
397 .chars_at(Point::new(selection.end.row + 1, 0));
398
399 for c in chars {
400 if c == '\n' {
401 break;
402 }
403 if c.is_whitespace() {
404 continue;
405 }
406 if snapshot
407 .language_at(selection.end)
408 .is_some_and(|language| language.config().brackets.is_closing_brace(c))
409 {
410 selection.end.row += 1;
411 selection.end.column = snapshot
412 .buffer_snapshot()
413 .line_len(MultiBufferRow(selection.end.row));
414 }
415 }
416 }
417 } else {
418 selection.start.column = 0;
419 // If the selection ends at the start of the line, we don't want to include it.
420 if selection.end.column == 0 && selection.start.row != selection.end.row {
421 selection.end.row -= 1;
422 }
423 selection.end.column = snapshot
424 .buffer_snapshot()
425 .line_len(MultiBufferRow(selection.end.row));
426 }
427
428 if let Some(prev_selection) = selections.last_mut()
429 && selection.start <= prev_selection.end
430 {
431 prev_selection.end = selection.end;
432 continue;
433 }
434
435 let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
436 if selection.id > latest_selection.id {
437 *latest_selection = selection.clone();
438 }
439 selections.push(selection);
440 }
441 let snapshot = &snapshot.buffer_snapshot();
442 let newest_selection = newest_selection.unwrap();
443
444 let mut codegen_ranges = Vec::new();
445 for (buffer, buffer_range, excerpt_id) in
446 snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
447 snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
448 }))
449 {
450 let anchor_range = Anchor::range_in_buffer(
451 excerpt_id,
452 buffer.anchor_before(buffer_range.start)..buffer.anchor_after(buffer_range.end),
453 );
454
455 codegen_ranges.push(anchor_range);
456
457 if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
458 telemetry::event!(
459 "Assistant Invoked",
460 kind = "inline",
461 phase = "invoked",
462 model = model.model.telemetry_id(),
463 model_provider = model.provider.id().to_string(),
464 language_name = buffer.language().map(|language| language.name().to_proto())
465 );
466
467 report_anthropic_event(
468 &model.model,
469 AnthropicEventData {
470 completion_type: language_model::AnthropicCompletionType::Editor,
471 event: language_model::AnthropicEventType::Invoked,
472 language_name: buffer.language().map(|language| language.name().to_proto()),
473 message_id: None,
474 },
475 cx,
476 );
477 }
478 }
479
480 Some((codegen_ranges, newest_selection))
481 }
482
483 fn batch_assist(
484 &mut self,
485 editor: &Entity<Editor>,
486 workspace: WeakEntity<Workspace>,
487 project: WeakEntity<Project>,
488 thread_store: Entity<ThreadStore>,
489 prompt_store: Option<Entity<PromptStore>>,
490 history: Option<WeakEntity<ThreadHistory>>,
491 initial_prompt: Option<String>,
492 window: &mut Window,
493 codegen_ranges: &[Range<Anchor>],
494 newest_selection: Option<Selection<Point>>,
495 initial_transaction_id: Option<TransactionId>,
496 cx: &mut App,
497 ) -> Option<InlineAssistId> {
498 let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
499
500 let assist_group_id = self.next_assist_group_id.post_inc();
501 let session_id = Uuid::new_v4();
502 let prompt_buffer = cx.new(|cx| {
503 MultiBuffer::singleton(
504 cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx)),
505 cx,
506 )
507 });
508
509 let mut assists = Vec::new();
510 let mut assist_to_focus = None;
511
512 for range in codegen_ranges {
513 let assist_id = self.next_assist_id.post_inc();
514 let codegen = cx.new(|cx| {
515 BufferCodegen::new(
516 editor.read(cx).buffer().clone(),
517 range.clone(),
518 initial_transaction_id,
519 session_id,
520 self.prompt_builder.clone(),
521 cx,
522 )
523 });
524
525 let editor_margins = Arc::new(Mutex::new(EditorMargins::default()));
526 let prompt_editor = cx.new(|cx| {
527 PromptEditor::new_buffer(
528 assist_id,
529 editor_margins,
530 self.prompt_history.clone(),
531 prompt_buffer.clone(),
532 codegen.clone(),
533 session_id,
534 self.fs.clone(),
535 thread_store.clone(),
536 prompt_store.clone(),
537 history.clone(),
538 project.clone(),
539 workspace.clone(),
540 window,
541 cx,
542 )
543 });
544
545 if let Some(newest_selection) = newest_selection.as_ref()
546 && assist_to_focus.is_none()
547 {
548 let focus_assist = if newest_selection.reversed {
549 range.start.to_point(&snapshot) == newest_selection.start
550 } else {
551 range.end.to_point(&snapshot) == newest_selection.end
552 };
553 if focus_assist {
554 assist_to_focus = Some(assist_id);
555 }
556 }
557
558 let [prompt_block_id, tool_description_block_id, end_block_id] =
559 self.insert_assist_blocks(&editor, &range, &prompt_editor, cx);
560
561 assists.push((
562 assist_id,
563 range.clone(),
564 prompt_editor,
565 prompt_block_id,
566 tool_description_block_id,
567 end_block_id,
568 ));
569 }
570
571 let editor_assists = self
572 .assists_by_editor
573 .entry(editor.downgrade())
574 .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
575
576 let assist_to_focus = if let Some(focus_id) = assist_to_focus {
577 Some(focus_id)
578 } else if assists.len() >= 1 {
579 Some(assists[0].0)
580 } else {
581 None
582 };
583
584 let mut assist_group = InlineAssistGroup::new();
585 for (
586 assist_id,
587 range,
588 prompt_editor,
589 prompt_block_id,
590 tool_description_block_id,
591 end_block_id,
592 ) in assists
593 {
594 let codegen = prompt_editor.read(cx).codegen().clone();
595
596 self.assists.insert(
597 assist_id,
598 InlineAssist::new(
599 assist_id,
600 assist_group_id,
601 editor,
602 &prompt_editor,
603 prompt_block_id,
604 tool_description_block_id,
605 end_block_id,
606 range,
607 codegen,
608 workspace.clone(),
609 window,
610 cx,
611 ),
612 );
613 assist_group.assist_ids.push(assist_id);
614 editor_assists.assist_ids.push(assist_id);
615 }
616
617 self.assist_groups.insert(assist_group_id, assist_group);
618
619 assist_to_focus
620 }
621
622 pub fn assist(
623 &mut self,
624 editor: &Entity<Editor>,
625 workspace: WeakEntity<Workspace>,
626 project: WeakEntity<Project>,
627 thread_store: Entity<ThreadStore>,
628 prompt_store: Option<Entity<PromptStore>>,
629 history: Option<WeakEntity<ThreadHistory>>,
630 initial_prompt: Option<String>,
631 window: &mut Window,
632 cx: &mut App,
633 ) -> Option<InlineAssistId> {
634 let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
635
636 let Some((codegen_ranges, newest_selection)) =
637 self.codegen_ranges(editor, &snapshot, window, cx)
638 else {
639 return None;
640 };
641
642 let assist_to_focus = self.batch_assist(
643 editor,
644 workspace,
645 project,
646 thread_store,
647 prompt_store,
648 history,
649 initial_prompt,
650 window,
651 &codegen_ranges,
652 Some(newest_selection),
653 None,
654 cx,
655 );
656
657 if let Some(assist_id) = assist_to_focus {
658 self.focus_assist(assist_id, window, cx);
659 }
660
661 assist_to_focus
662 }
663
664 pub fn suggest_assist(
665 &mut self,
666 editor: &Entity<Editor>,
667 mut range: Range<Anchor>,
668 initial_prompt: String,
669 initial_transaction_id: Option<TransactionId>,
670 focus: bool,
671 workspace: Entity<Workspace>,
672 thread_store: Entity<ThreadStore>,
673 prompt_store: Option<Entity<PromptStore>>,
674 history: Option<WeakEntity<ThreadHistory>>,
675 window: &mut Window,
676 cx: &mut App,
677 ) -> InlineAssistId {
678 let buffer = editor.read(cx).buffer().clone();
679 {
680 let snapshot = buffer.read(cx).read(cx);
681 range.start = range.start.bias_left(&snapshot);
682 range.end = range.end.bias_right(&snapshot);
683 }
684
685 let project = workspace.read(cx).project().downgrade();
686
687 let assist_id = self
688 .batch_assist(
689 editor,
690 workspace.downgrade(),
691 project,
692 thread_store,
693 prompt_store,
694 history,
695 Some(initial_prompt),
696 window,
697 &[range],
698 None,
699 initial_transaction_id,
700 cx,
701 )
702 .expect("batch_assist returns an id if there's only one range");
703
704 if focus {
705 self.focus_assist(assist_id, window, cx);
706 }
707
708 assist_id
709 }
710
711 fn insert_assist_blocks(
712 &self,
713 editor: &Entity<Editor>,
714 range: &Range<Anchor>,
715 prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
716 cx: &mut App,
717 ) -> [CustomBlockId; 3] {
718 let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
719 prompt_editor
720 .editor
721 .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
722 });
723 let assist_blocks = vec![
724 BlockProperties {
725 style: BlockStyle::Sticky,
726 placement: BlockPlacement::Above(range.start),
727 height: Some(prompt_editor_height),
728 render: build_assist_editor_renderer(prompt_editor),
729 priority: 0,
730 },
731 // Placeholder for tool description - will be updated dynamically
732 BlockProperties {
733 style: BlockStyle::Flex,
734 placement: BlockPlacement::Below(range.end),
735 height: Some(0),
736 render: Arc::new(|_cx| div().into_any_element()),
737 priority: 0,
738 },
739 BlockProperties {
740 style: BlockStyle::Sticky,
741 placement: BlockPlacement::Below(range.end),
742 height: None,
743 render: Arc::new(|cx| {
744 v_flex()
745 .h_full()
746 .w_full()
747 .border_t_1()
748 .border_color(cx.theme().status().info_border)
749 .into_any_element()
750 }),
751 priority: 0,
752 },
753 ];
754
755 editor.update(cx, |editor, cx| {
756 let block_ids = editor.insert_blocks(assist_blocks, None, cx);
757 [block_ids[0], block_ids[1], block_ids[2]]
758 })
759 }
760
761 fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
762 let assist = &self.assists[&assist_id];
763 let Some(decorations) = assist.decorations.as_ref() else {
764 return;
765 };
766 let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
767 let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
768
769 assist_group.active_assist_id = Some(assist_id);
770 if assist_group.linked {
771 for assist_id in &assist_group.assist_ids {
772 if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
773 decorations.prompt_editor.update(cx, |prompt_editor, cx| {
774 prompt_editor.set_show_cursor_when_unfocused(true, cx)
775 });
776 }
777 }
778 }
779
780 assist
781 .editor
782 .update(cx, |editor, cx| {
783 let scroll_top = editor.scroll_position(cx).y;
784 let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
785 editor_assists.scroll_lock = editor
786 .row_for_block(decorations.prompt_block_id, cx)
787 .map(|row| row.as_f64())
788 .filter(|prompt_row| (scroll_top..scroll_bottom).contains(&prompt_row))
789 .map(|prompt_row| InlineAssistScrollLock {
790 assist_id,
791 distance_from_top: prompt_row - scroll_top,
792 });
793 })
794 .ok();
795 }
796
797 fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
798 let assist = &self.assists[&assist_id];
799 let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
800 if assist_group.active_assist_id == Some(assist_id) {
801 assist_group.active_assist_id = None;
802 if assist_group.linked {
803 for assist_id in &assist_group.assist_ids {
804 if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
805 decorations.prompt_editor.update(cx, |prompt_editor, cx| {
806 prompt_editor.set_show_cursor_when_unfocused(false, cx)
807 });
808 }
809 }
810 }
811 }
812 }
813
814 fn handle_prompt_editor_event(
815 &mut self,
816 prompt_editor: Entity<PromptEditor<BufferCodegen>>,
817 event: &PromptEditorEvent,
818 window: &mut Window,
819 cx: &mut App,
820 ) {
821 let assist_id = prompt_editor.read(cx).id();
822 match event {
823 PromptEditorEvent::StartRequested => {
824 self.start_assist(assist_id, window, cx);
825 }
826 PromptEditorEvent::StopRequested => {
827 self.stop_assist(assist_id, cx);
828 }
829 PromptEditorEvent::ConfirmRequested { execute: _ } => {
830 self.finish_assist(assist_id, false, window, cx);
831 }
832 PromptEditorEvent::CancelRequested => {
833 self.finish_assist(assist_id, true, window, cx);
834 }
835 PromptEditorEvent::Resized { .. } => {
836 // This only matters for the terminal inline assistant
837 }
838 }
839 }
840
841 fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
842 let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
843 return;
844 };
845
846 if editor.read(cx).selections.count() == 1 {
847 let (selection, buffer) = editor.update(cx, |editor, cx| {
848 (
849 editor
850 .selections
851 .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
852 editor.buffer().read(cx).snapshot(cx),
853 )
854 });
855 for assist_id in &editor_assists.assist_ids {
856 let assist = &self.assists[assist_id];
857 let assist_range = assist.range.to_offset(&buffer);
858 if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
859 {
860 if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
861 self.dismiss_assist(*assist_id, window, cx);
862 } else {
863 self.finish_assist(*assist_id, false, window, cx);
864 }
865
866 return;
867 }
868 }
869 }
870
871 cx.propagate();
872 }
873
874 fn handle_editor_cancel(&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
879 if editor.read(cx).selections.count() == 1 {
880 let (selection, buffer) = editor.update(cx, |editor, cx| {
881 (
882 editor
883 .selections
884 .newest::<MultiBufferOffset>(&editor.display_snapshot(cx)),
885 editor.buffer().read(cx).snapshot(cx),
886 )
887 });
888 let mut closest_assist_fallback = None;
889 for assist_id in &editor_assists.assist_ids {
890 let assist = &self.assists[assist_id];
891 let assist_range = assist.range.to_offset(&buffer);
892 if assist.decorations.is_some() {
893 if assist_range.contains(&selection.start)
894 && assist_range.contains(&selection.end)
895 {
896 self.focus_assist(*assist_id, window, cx);
897 return;
898 } else {
899 let distance_from_selection = assist_range
900 .start
901 .0
902 .abs_diff(selection.start.0)
903 .min(assist_range.start.0.abs_diff(selection.end.0))
904 + assist_range
905 .end
906 .0
907 .abs_diff(selection.start.0)
908 .min(assist_range.end.0.abs_diff(selection.end.0));
909 match closest_assist_fallback {
910 Some((_, old_distance)) => {
911 if distance_from_selection < old_distance {
912 closest_assist_fallback =
913 Some((assist_id, distance_from_selection));
914 }
915 }
916 None => {
917 closest_assist_fallback = Some((assist_id, distance_from_selection))
918 }
919 }
920 }
921 }
922 }
923
924 if let Some((&assist_id, _)) = closest_assist_fallback {
925 self.focus_assist(assist_id, window, cx);
926 }
927 }
928
929 cx.propagate();
930 }
931
932 fn handle_editor_release(
933 &mut self,
934 editor: WeakEntity<Editor>,
935 window: &mut Window,
936 cx: &mut App,
937 ) {
938 if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
939 for assist_id in editor_assists.assist_ids.clone() {
940 self.finish_assist(assist_id, true, window, cx);
941 }
942 }
943 }
944
945 fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
946 let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
947 return;
948 };
949 let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
950 return;
951 };
952 let assist = &self.assists[&scroll_lock.assist_id];
953 let Some(decorations) = assist.decorations.as_ref() else {
954 return;
955 };
956
957 editor.update(cx, |editor, cx| {
958 let scroll_position = editor.scroll_position(cx);
959 let target_scroll_top = editor
960 .row_for_block(decorations.prompt_block_id, cx)?
961 .as_f64()
962 - scroll_lock.distance_from_top;
963 if target_scroll_top != scroll_position.y {
964 editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
965 }
966 Some(())
967 });
968 }
969
970 fn handle_editor_event(
971 &mut self,
972 editor: Entity<Editor>,
973 event: &EditorEvent,
974 window: &mut Window,
975 cx: &mut App,
976 ) {
977 let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
978 return;
979 };
980
981 match event {
982 EditorEvent::Edited { transaction_id } => {
983 let buffer = editor.read(cx).buffer().read(cx);
984 let edited_ranges =
985 buffer.edited_ranges_for_transaction::<MultiBufferOffset>(*transaction_id, cx);
986 let snapshot = buffer.snapshot(cx);
987
988 for assist_id in editor_assists.assist_ids.clone() {
989 let assist = &self.assists[&assist_id];
990 if matches!(
991 assist.codegen.read(cx).status(cx),
992 CodegenStatus::Error(_) | CodegenStatus::Done
993 ) {
994 let assist_range = assist.range.to_offset(&snapshot);
995 if edited_ranges
996 .iter()
997 .any(|range| range.overlaps(&assist_range))
998 {
999 self.finish_assist(assist_id, false, window, cx);
1000 }
1001 }
1002 }
1003 }
1004 EditorEvent::ScrollPositionChanged { .. } => {
1005 if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
1006 let assist = &self.assists[&scroll_lock.assist_id];
1007 if let Some(decorations) = assist.decorations.as_ref() {
1008 let distance_from_top = editor.update(cx, |editor, cx| {
1009 let scroll_top = editor.scroll_position(cx).y;
1010 let prompt_row = editor
1011 .row_for_block(decorations.prompt_block_id, cx)?
1012 .0 as ScrollOffset;
1013 Some(prompt_row - scroll_top)
1014 });
1015
1016 if distance_from_top.is_none_or(|distance_from_top| {
1017 distance_from_top != scroll_lock.distance_from_top
1018 }) {
1019 editor_assists.scroll_lock = None;
1020 }
1021 }
1022 }
1023 }
1024 EditorEvent::SelectionsChanged { .. } => {
1025 for assist_id in editor_assists.assist_ids.clone() {
1026 let assist = &self.assists[&assist_id];
1027 if let Some(decorations) = assist.decorations.as_ref()
1028 && decorations
1029 .prompt_editor
1030 .focus_handle(cx)
1031 .is_focused(window)
1032 {
1033 return;
1034 }
1035 }
1036
1037 editor_assists.scroll_lock = None;
1038 }
1039 _ => {}
1040 }
1041 }
1042
1043 pub fn finish_assist(
1044 &mut self,
1045 assist_id: InlineAssistId,
1046 undo: bool,
1047 window: &mut Window,
1048 cx: &mut App,
1049 ) {
1050 if let Some(assist) = self.assists.get(&assist_id) {
1051 let assist_group_id = assist.group_id;
1052 if self.assist_groups[&assist_group_id].linked {
1053 for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1054 self.finish_assist(assist_id, undo, window, cx);
1055 }
1056 return;
1057 }
1058 }
1059
1060 self.dismiss_assist(assist_id, window, cx);
1061
1062 if let Some(assist) = self.assists.remove(&assist_id) {
1063 if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
1064 {
1065 entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1066 if entry.get().assist_ids.is_empty() {
1067 entry.remove();
1068 }
1069 }
1070
1071 if let hash_map::Entry::Occupied(mut entry) =
1072 self.assists_by_editor.entry(assist.editor.clone())
1073 {
1074 entry.get_mut().assist_ids.retain(|id| *id != assist_id);
1075 if entry.get().assist_ids.is_empty() {
1076 entry.remove();
1077 if let Some(editor) = assist.editor.upgrade() {
1078 self.update_editor_highlights(&editor, cx);
1079 }
1080 } else {
1081 entry.get_mut().highlight_updates.send(()).ok();
1082 }
1083 }
1084
1085 let active_alternative = assist.codegen.read(cx).active_alternative().clone();
1086 if let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() {
1087 let language_name = assist.editor.upgrade().and_then(|editor| {
1088 let multibuffer = editor.read(cx).buffer().read(cx);
1089 let snapshot = multibuffer.snapshot(cx);
1090 let ranges =
1091 snapshot.range_to_buffer_ranges(assist.range.start..=assist.range.end);
1092 ranges
1093 .first()
1094 .and_then(|(buffer, _, _)| buffer.language())
1095 .map(|language| language.name().0.to_string())
1096 });
1097
1098 let codegen = assist.codegen.read(cx);
1099 let session_id = codegen.session_id();
1100 let message_id = active_alternative.read(cx).message_id.clone();
1101 let model_telemetry_id = model.model.telemetry_id();
1102 let model_provider_id = model.model.provider_id().to_string();
1103
1104 let (phase, event_type, anthropic_event_type) = if undo {
1105 (
1106 "rejected",
1107 "Assistant Response Rejected",
1108 language_model::AnthropicEventType::Reject,
1109 )
1110 } else {
1111 (
1112 "accepted",
1113 "Assistant Response Accepted",
1114 language_model::AnthropicEventType::Accept,
1115 )
1116 };
1117
1118 telemetry::event!(
1119 event_type,
1120 phase,
1121 session_id = session_id.to_string(),
1122 kind = "inline",
1123 model = model_telemetry_id,
1124 model_provider = model_provider_id,
1125 language_name = language_name,
1126 message_id = message_id.as_deref(),
1127 );
1128
1129 report_anthropic_event(
1130 &model.model,
1131 language_model::AnthropicEventData {
1132 completion_type: language_model::AnthropicCompletionType::Editor,
1133 event: anthropic_event_type,
1134 language_name,
1135 message_id,
1136 },
1137 cx,
1138 );
1139 }
1140
1141 if undo {
1142 assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
1143 } else {
1144 self.confirmed_assists.insert(assist_id, active_alternative);
1145 }
1146 }
1147 }
1148
1149 fn dismiss_assist(
1150 &mut self,
1151 assist_id: InlineAssistId,
1152 window: &mut Window,
1153 cx: &mut App,
1154 ) -> bool {
1155 let Some(assist) = self.assists.get_mut(&assist_id) else {
1156 return false;
1157 };
1158 let Some(editor) = assist.editor.upgrade() else {
1159 return false;
1160 };
1161 let Some(decorations) = assist.decorations.take() else {
1162 return false;
1163 };
1164
1165 editor.update(cx, |editor, cx| {
1166 let mut to_remove = decorations.removed_line_block_ids;
1167 to_remove.insert(decorations.prompt_block_id);
1168 to_remove.insert(decorations.end_block_id);
1169 if let Some(tool_description_block_id) = decorations.model_explanation {
1170 to_remove.insert(tool_description_block_id);
1171 }
1172 editor.remove_blocks(to_remove, None, cx);
1173 });
1174
1175 if decorations
1176 .prompt_editor
1177 .focus_handle(cx)
1178 .contains_focused(window, cx)
1179 {
1180 self.focus_next_assist(assist_id, window, cx);
1181 }
1182
1183 if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
1184 if editor_assists
1185 .scroll_lock
1186 .as_ref()
1187 .is_some_and(|lock| lock.assist_id == assist_id)
1188 {
1189 editor_assists.scroll_lock = None;
1190 }
1191 editor_assists.highlight_updates.send(()).ok();
1192 }
1193
1194 true
1195 }
1196
1197 fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1198 let Some(assist) = self.assists.get(&assist_id) else {
1199 return;
1200 };
1201
1202 let assist_group = &self.assist_groups[&assist.group_id];
1203 let assist_ix = assist_group
1204 .assist_ids
1205 .iter()
1206 .position(|id| *id == assist_id)
1207 .unwrap();
1208 let assist_ids = assist_group
1209 .assist_ids
1210 .iter()
1211 .skip(assist_ix + 1)
1212 .chain(assist_group.assist_ids.iter().take(assist_ix));
1213
1214 for assist_id in assist_ids {
1215 let assist = &self.assists[assist_id];
1216 if assist.decorations.is_some() {
1217 self.focus_assist(*assist_id, window, cx);
1218 return;
1219 }
1220 }
1221
1222 assist
1223 .editor
1224 .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
1225 .ok();
1226 }
1227
1228 fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1229 let Some(assist) = self.assists.get(&assist_id) else {
1230 return;
1231 };
1232
1233 if let Some(decorations) = assist.decorations.as_ref() {
1234 decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1235 prompt_editor.editor.update(cx, |editor, cx| {
1236 window.focus(&editor.focus_handle(cx), cx);
1237 editor.select_all(&SelectAll, window, cx);
1238 })
1239 });
1240 }
1241
1242 self.scroll_to_assist(assist_id, window, cx);
1243 }
1244
1245 pub fn scroll_to_assist(
1246 &mut self,
1247 assist_id: InlineAssistId,
1248 window: &mut Window,
1249 cx: &mut App,
1250 ) {
1251 let Some(assist) = self.assists.get(&assist_id) else {
1252 return;
1253 };
1254 let Some(editor) = assist.editor.upgrade() else {
1255 return;
1256 };
1257
1258 let position = assist.range.start;
1259 editor.update(cx, |editor, cx| {
1260 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1261 selections.select_anchor_ranges([position..position])
1262 });
1263
1264 let mut scroll_target_range = None;
1265 if let Some(decorations) = assist.decorations.as_ref() {
1266 scroll_target_range = maybe!({
1267 let top = editor.row_for_block(decorations.prompt_block_id, cx)?.0 as f64;
1268 let bottom = editor.row_for_block(decorations.end_block_id, cx)?.0 as f64;
1269 Some((top, bottom))
1270 });
1271 if scroll_target_range.is_none() {
1272 log::error!("bug: failed to find blocks for scrolling to inline assist");
1273 }
1274 }
1275 let scroll_target_range = scroll_target_range.unwrap_or_else(|| {
1276 let snapshot = editor.snapshot(window, cx);
1277 let start_row = assist
1278 .range
1279 .start
1280 .to_display_point(&snapshot.display_snapshot)
1281 .row();
1282 let top = start_row.0 as ScrollOffset;
1283 let bottom = top + 1.0;
1284 (top, bottom)
1285 });
1286 let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1287 let vertical_scroll_margin = editor.vertical_scroll_margin() as ScrollOffset;
1288 let scroll_target_top = (scroll_target_range.0 - vertical_scroll_margin)
1289 // Don't scroll up too far in the case of a large vertical_scroll_margin.
1290 .max(scroll_target_range.0 - height_in_lines / 2.0);
1291 let scroll_target_bottom = (scroll_target_range.1 + vertical_scroll_margin)
1292 // Don't scroll down past where the top would still be visible.
1293 .min(scroll_target_top + height_in_lines);
1294
1295 let scroll_top = editor.scroll_position(cx).y;
1296 let scroll_bottom = scroll_top + height_in_lines;
1297
1298 if scroll_target_top < scroll_top {
1299 editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1300 } else if scroll_target_bottom > scroll_bottom {
1301 editor.set_scroll_position(
1302 point(0., scroll_target_bottom - height_in_lines),
1303 window,
1304 cx,
1305 );
1306 }
1307 });
1308 }
1309
1310 fn unlink_assist_group(
1311 &mut self,
1312 assist_group_id: InlineAssistGroupId,
1313 window: &mut Window,
1314 cx: &mut App,
1315 ) -> Vec<InlineAssistId> {
1316 let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1317 assist_group.linked = false;
1318
1319 for assist_id in &assist_group.assist_ids {
1320 let assist = self.assists.get_mut(assist_id).unwrap();
1321 if let Some(editor_decorations) = assist.decorations.as_ref() {
1322 editor_decorations
1323 .prompt_editor
1324 .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1325 }
1326 }
1327 assist_group.assist_ids.clone()
1328 }
1329
1330 pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1331 let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1332 assist
1333 } else {
1334 return;
1335 };
1336
1337 let assist_group_id = assist.group_id;
1338 if self.assist_groups[&assist_group_id].linked {
1339 for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1340 self.start_assist(assist_id, window, cx);
1341 }
1342 return;
1343 }
1344
1345 let Some((user_prompt, mention_set)) = assist.user_prompt(cx).zip(assist.mention_set(cx))
1346 else {
1347 return;
1348 };
1349
1350 self.prompt_history.retain(|prompt| *prompt != user_prompt);
1351 self.prompt_history.push_back(user_prompt.clone());
1352 if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1353 self.prompt_history.pop_front();
1354 }
1355
1356 let Some(ConfiguredModel { model, .. }) =
1357 LanguageModelRegistry::read_global(cx).inline_assistant_model()
1358 else {
1359 return;
1360 };
1361
1362 let context_task = load_context(&mention_set, cx).shared();
1363 assist
1364 .codegen
1365 .update(cx, |codegen, cx| {
1366 codegen.start(model, user_prompt, context_task, cx)
1367 })
1368 .log_err();
1369 }
1370
1371 pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1372 let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1373 assist
1374 } else {
1375 return;
1376 };
1377
1378 assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1379 }
1380
1381 fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1382 let mut gutter_pending_ranges = Vec::new();
1383 let mut gutter_transformed_ranges = Vec::new();
1384 let mut foreground_ranges = Vec::new();
1385 let mut inserted_row_ranges = Vec::new();
1386 let empty_assist_ids = Vec::new();
1387 let assist_ids = self
1388 .assists_by_editor
1389 .get(&editor.downgrade())
1390 .map_or(&empty_assist_ids, |editor_assists| {
1391 &editor_assists.assist_ids
1392 });
1393
1394 for assist_id in assist_ids {
1395 if let Some(assist) = self.assists.get(assist_id) {
1396 let codegen = assist.codegen.read(cx);
1397 let buffer = codegen.buffer(cx).read(cx).read(cx);
1398 foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1399
1400 let pending_range =
1401 codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1402 if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1403 gutter_pending_ranges.push(pending_range);
1404 }
1405
1406 if let Some(edit_position) = codegen.edit_position(cx) {
1407 let edited_range = assist.range.start..edit_position;
1408 if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1409 gutter_transformed_ranges.push(edited_range);
1410 }
1411 }
1412
1413 if assist.decorations.is_some() {
1414 inserted_row_ranges
1415 .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1416 }
1417 }
1418 }
1419
1420 let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1421 merge_ranges(&mut foreground_ranges, &snapshot);
1422 merge_ranges(&mut gutter_pending_ranges, &snapshot);
1423 merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1424 editor.update(cx, |editor, cx| {
1425 enum GutterPendingRange {}
1426 if gutter_pending_ranges.is_empty() {
1427 editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1428 } else {
1429 editor.highlight_gutter::<GutterPendingRange>(
1430 gutter_pending_ranges,
1431 |cx| cx.theme().status().info_background,
1432 cx,
1433 )
1434 }
1435
1436 enum GutterTransformedRange {}
1437 if gutter_transformed_ranges.is_empty() {
1438 editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1439 } else {
1440 editor.highlight_gutter::<GutterTransformedRange>(
1441 gutter_transformed_ranges,
1442 |cx| cx.theme().status().info,
1443 cx,
1444 )
1445 }
1446
1447 if foreground_ranges.is_empty() {
1448 editor.clear_highlights(HighlightKey::InlineAssist, cx);
1449 } else {
1450 editor.highlight_text(
1451 HighlightKey::InlineAssist,
1452 foreground_ranges,
1453 HighlightStyle {
1454 fade_out: Some(0.6),
1455 ..Default::default()
1456 },
1457 cx,
1458 );
1459 }
1460
1461 editor.clear_row_highlights::<InlineAssist>();
1462 for row_range in inserted_row_ranges {
1463 editor.highlight_rows::<InlineAssist>(
1464 row_range,
1465 cx.theme().status().info_background,
1466 Default::default(),
1467 cx,
1468 );
1469 }
1470 });
1471 }
1472
1473 fn update_editor_blocks(
1474 &mut self,
1475 editor: &Entity<Editor>,
1476 assist_id: InlineAssistId,
1477 window: &mut Window,
1478 cx: &mut App,
1479 ) {
1480 let Some(assist) = self.assists.get_mut(&assist_id) else {
1481 return;
1482 };
1483 let Some(decorations) = assist.decorations.as_mut() else {
1484 return;
1485 };
1486
1487 let codegen = assist.codegen.read(cx);
1488 let old_snapshot = codegen.snapshot(cx);
1489 let old_buffer = codegen.old_buffer(cx);
1490 let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1491
1492 editor.update(cx, |editor, cx| {
1493 let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1494 editor.remove_blocks(old_blocks, None, cx);
1495
1496 let mut new_blocks = Vec::new();
1497 for (new_row, old_row_range) in deleted_row_ranges {
1498 let (_, start, _) = old_snapshot
1499 .point_to_buffer_point(Point::new(*old_row_range.start(), 0))
1500 .unwrap();
1501 let (_, end, _) = old_snapshot
1502 .point_to_buffer_point(Point::new(
1503 *old_row_range.end(),
1504 old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1505 ))
1506 .unwrap();
1507
1508 let deleted_lines_editor = cx.new(|cx| {
1509 let multi_buffer =
1510 cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1511 multi_buffer.update(cx, |multi_buffer, cx| {
1512 multi_buffer.set_excerpts_for_buffer(
1513 old_buffer.clone(),
1514 // todo(lw): start and end might come from different snapshots!
1515 [start..end],
1516 0,
1517 cx,
1518 );
1519 });
1520
1521 enum DeletedLines {}
1522 let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1523 editor.disable_scrollbars_and_minimap(window, cx);
1524 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1525 editor.set_show_wrap_guides(false, cx);
1526 editor.set_show_gutter(false, cx);
1527 editor.set_offset_content(false, cx);
1528 editor.scroll_manager.set_forbid_vertical_scroll(true);
1529 editor.set_read_only(true);
1530 editor.set_show_edit_predictions(Some(false), window, cx);
1531 editor.highlight_rows::<DeletedLines>(
1532 Anchor::min()..Anchor::max(),
1533 cx.theme().status().deleted_background,
1534 Default::default(),
1535 cx,
1536 );
1537 editor
1538 });
1539
1540 let height =
1541 deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1542 new_blocks.push(BlockProperties {
1543 placement: BlockPlacement::Above(new_row),
1544 height: Some(height),
1545 style: BlockStyle::Flex,
1546 render: Arc::new(move |cx| {
1547 div()
1548 .block_mouse_except_scroll()
1549 .bg(cx.theme().status().deleted_background)
1550 .size_full()
1551 .h(height as f32 * cx.window.line_height())
1552 .pl(cx.margins.gutter.full_width())
1553 .child(deleted_lines_editor.clone())
1554 .into_any_element()
1555 }),
1556 priority: 0,
1557 });
1558 }
1559
1560 decorations.removed_line_block_ids = editor
1561 .insert_blocks(new_blocks, None, cx)
1562 .into_iter()
1563 .collect();
1564 })
1565 }
1566
1567 fn resolve_inline_assist_target(
1568 workspace: &mut Workspace,
1569 window: &mut Window,
1570 cx: &mut App,
1571 ) -> Option<InlineAssistTarget> {
1572 if let Some(terminal_panel) = workspace.panel::<TerminalPanel>(cx)
1573 && terminal_panel
1574 .read(cx)
1575 .focus_handle(cx)
1576 .contains_focused(window, cx)
1577 && let Some(terminal_view) = terminal_panel.read(cx).pane().and_then(|pane| {
1578 pane.read(cx)
1579 .active_item()
1580 .and_then(|t| t.downcast::<TerminalView>())
1581 })
1582 {
1583 return Some(InlineAssistTarget::Terminal(terminal_view));
1584 }
1585
1586 if let Some(workspace_editor) = workspace
1587 .active_item(cx)
1588 .and_then(|item| item.act_as::<Editor>(cx))
1589 {
1590 Some(InlineAssistTarget::Editor(workspace_editor))
1591 } else {
1592 workspace
1593 .active_item(cx)
1594 .and_then(|item| item.act_as::<TerminalView>(cx))
1595 .map(InlineAssistTarget::Terminal)
1596 }
1597 }
1598
1599 #[cfg(any(test, feature = "test-support"))]
1600 pub fn set_completion_receiver(
1601 &mut self,
1602 sender: mpsc::UnboundedSender<anyhow::Result<InlineAssistId>>,
1603 ) {
1604 self._inline_assistant_completions = Some(sender);
1605 }
1606
1607 #[cfg(any(test, feature = "test-support"))]
1608 pub fn get_codegen(
1609 &mut self,
1610 assist_id: InlineAssistId,
1611 cx: &mut App,
1612 ) -> Option<Entity<CodegenAlternative>> {
1613 self.assists.get(&assist_id).map(|inline_assist| {
1614 inline_assist
1615 .codegen
1616 .update(cx, |codegen, _cx| codegen.active_alternative().clone())
1617 })
1618 }
1619}
1620
1621struct EditorInlineAssists {
1622 assist_ids: Vec<InlineAssistId>,
1623 scroll_lock: Option<InlineAssistScrollLock>,
1624 highlight_updates: watch::Sender<()>,
1625 _update_highlights: Task<Result<()>>,
1626 _subscriptions: Vec<gpui::Subscription>,
1627}
1628
1629struct InlineAssistScrollLock {
1630 assist_id: InlineAssistId,
1631 distance_from_top: ScrollOffset,
1632}
1633
1634impl EditorInlineAssists {
1635 fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1636 let (highlight_updates_tx, mut highlight_updates_rx) = watch::channel(());
1637 Self {
1638 assist_ids: Vec::new(),
1639 scroll_lock: None,
1640 highlight_updates: highlight_updates_tx,
1641 _update_highlights: cx.spawn({
1642 let editor = editor.downgrade();
1643 async move |cx| {
1644 while let Ok(()) = highlight_updates_rx.changed().await {
1645 let editor = editor.upgrade().context("editor was dropped")?;
1646 cx.update_global(|assistant: &mut InlineAssistant, cx| {
1647 assistant.update_editor_highlights(&editor, cx);
1648 });
1649 }
1650 Ok(())
1651 }
1652 }),
1653 _subscriptions: vec![
1654 cx.observe_release_in(editor, window, {
1655 let editor = editor.downgrade();
1656 |_, window, cx| {
1657 InlineAssistant::update_global(cx, |this, cx| {
1658 this.handle_editor_release(editor, window, cx);
1659 })
1660 }
1661 }),
1662 window.observe(editor, cx, move |editor, window, cx| {
1663 InlineAssistant::update_global(cx, |this, cx| {
1664 this.handle_editor_change(editor, window, cx)
1665 })
1666 }),
1667 window.subscribe(editor, cx, move |editor, event, window, cx| {
1668 InlineAssistant::update_global(cx, |this, cx| {
1669 this.handle_editor_event(editor, event, window, cx)
1670 })
1671 }),
1672 editor.update(cx, |editor, cx| {
1673 let editor_handle = cx.entity().downgrade();
1674 editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1675 InlineAssistant::update_global(cx, |this, cx| {
1676 if let Some(editor) = editor_handle.upgrade() {
1677 this.handle_editor_newline(editor, window, cx)
1678 }
1679 })
1680 })
1681 }),
1682 editor.update(cx, |editor, cx| {
1683 let editor_handle = cx.entity().downgrade();
1684 editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1685 InlineAssistant::update_global(cx, |this, cx| {
1686 if let Some(editor) = editor_handle.upgrade() {
1687 this.handle_editor_cancel(editor, window, cx)
1688 }
1689 })
1690 })
1691 }),
1692 ],
1693 }
1694 }
1695}
1696
1697struct InlineAssistGroup {
1698 assist_ids: Vec<InlineAssistId>,
1699 linked: bool,
1700 active_assist_id: Option<InlineAssistId>,
1701}
1702
1703impl InlineAssistGroup {
1704 fn new() -> Self {
1705 Self {
1706 assist_ids: Vec::new(),
1707 linked: true,
1708 active_assist_id: None,
1709 }
1710 }
1711}
1712
1713fn build_assist_editor_renderer(editor: &Entity<PromptEditor<BufferCodegen>>) -> RenderBlock {
1714 let editor = editor.clone();
1715
1716 Arc::new(move |cx: &mut BlockContext| {
1717 let editor_margins = editor.read(cx).editor_margins();
1718
1719 *editor_margins.lock() = *cx.margins;
1720 editor.clone().into_any_element()
1721 })
1722}
1723
1724#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1725struct InlineAssistGroupId(usize);
1726
1727impl InlineAssistGroupId {
1728 fn post_inc(&mut self) -> InlineAssistGroupId {
1729 let id = *self;
1730 self.0 += 1;
1731 id
1732 }
1733}
1734
1735pub struct InlineAssist {
1736 group_id: InlineAssistGroupId,
1737 range: Range<Anchor>,
1738 editor: WeakEntity<Editor>,
1739 decorations: Option<InlineAssistDecorations>,
1740 codegen: Entity<BufferCodegen>,
1741 _subscriptions: Vec<Subscription>,
1742 workspace: WeakEntity<Workspace>,
1743}
1744
1745impl InlineAssist {
1746 fn new(
1747 assist_id: InlineAssistId,
1748 group_id: InlineAssistGroupId,
1749 editor: &Entity<Editor>,
1750 prompt_editor: &Entity<PromptEditor<BufferCodegen>>,
1751 prompt_block_id: CustomBlockId,
1752 tool_description_block_id: CustomBlockId,
1753 end_block_id: CustomBlockId,
1754 range: Range<Anchor>,
1755 codegen: Entity<BufferCodegen>,
1756 workspace: WeakEntity<Workspace>,
1757 window: &mut Window,
1758 cx: &mut App,
1759 ) -> Self {
1760 let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
1761 InlineAssist {
1762 group_id,
1763 editor: editor.downgrade(),
1764 decorations: Some(InlineAssistDecorations {
1765 prompt_block_id,
1766 prompt_editor: prompt_editor.clone(),
1767 removed_line_block_ids: Default::default(),
1768 model_explanation: Some(tool_description_block_id),
1769 end_block_id,
1770 }),
1771 range,
1772 codegen: codegen.clone(),
1773 workspace,
1774 _subscriptions: vec![
1775 window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
1776 InlineAssistant::update_global(cx, |this, cx| {
1777 this.handle_prompt_editor_focus_in(assist_id, cx)
1778 })
1779 }),
1780 window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
1781 InlineAssistant::update_global(cx, |this, cx| {
1782 this.handle_prompt_editor_focus_out(assist_id, cx)
1783 })
1784 }),
1785 window.subscribe(prompt_editor, cx, |prompt_editor, event, window, cx| {
1786 InlineAssistant::update_global(cx, |this, cx| {
1787 this.handle_prompt_editor_event(prompt_editor, event, window, cx)
1788 })
1789 }),
1790 window.observe(&codegen, cx, {
1791 let editor = editor.downgrade();
1792 move |_, window, cx| {
1793 if let Some(editor) = editor.upgrade() {
1794 InlineAssistant::update_global(cx, |this, cx| {
1795 if let Some(editor_assists) =
1796 this.assists_by_editor.get_mut(&editor.downgrade())
1797 {
1798 editor_assists.highlight_updates.send(()).ok();
1799 }
1800
1801 this.update_editor_blocks(&editor, assist_id, window, cx);
1802 })
1803 }
1804 }
1805 }),
1806 window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
1807 InlineAssistant::update_global(cx, |this, cx| match event {
1808 CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
1809 CodegenEvent::Finished => {
1810 let assist = if let Some(assist) = this.assists.get(&assist_id) {
1811 assist
1812 } else {
1813 return;
1814 };
1815
1816 if let CodegenStatus::Error(error) = codegen.read(cx).status(cx)
1817 && assist.decorations.is_none()
1818 && let Some(workspace) = assist.workspace.upgrade()
1819 {
1820 #[cfg(any(test, feature = "test-support"))]
1821 if let Some(sender) = &mut this._inline_assistant_completions {
1822 sender
1823 .unbounded_send(Err(anyhow::anyhow!(
1824 "Inline assistant error: {}",
1825 error
1826 )))
1827 .ok();
1828 }
1829
1830 let error = format!("Inline assistant error: {}", error);
1831 workspace.update(cx, |workspace, cx| {
1832 struct InlineAssistantError;
1833
1834 let id = NotificationId::composite::<InlineAssistantError>(
1835 assist_id.0,
1836 );
1837
1838 workspace.show_toast(Toast::new(id, error), cx);
1839 })
1840 } else {
1841 #[cfg(any(test, feature = "test-support"))]
1842 if let Some(sender) = &mut this._inline_assistant_completions {
1843 sender.unbounded_send(Ok(assist_id)).ok();
1844 }
1845 }
1846
1847 if assist.decorations.is_none() {
1848 this.finish_assist(assist_id, false, window, cx);
1849 }
1850 }
1851 })
1852 }),
1853 ],
1854 }
1855 }
1856
1857 fn user_prompt(&self, cx: &App) -> Option<String> {
1858 let decorations = self.decorations.as_ref()?;
1859 Some(decorations.prompt_editor.read(cx).prompt(cx))
1860 }
1861
1862 fn mention_set(&self, cx: &App) -> Option<Entity<MentionSet>> {
1863 let decorations = self.decorations.as_ref()?;
1864 Some(decorations.prompt_editor.read(cx).mention_set().clone())
1865 }
1866}
1867
1868struct InlineAssistDecorations {
1869 prompt_block_id: CustomBlockId,
1870 prompt_editor: Entity<PromptEditor<BufferCodegen>>,
1871 removed_line_block_ids: HashSet<CustomBlockId>,
1872 model_explanation: Option<CustomBlockId>,
1873 end_block_id: CustomBlockId,
1874}
1875
1876struct AssistantCodeActionProvider {
1877 editor: WeakEntity<Editor>,
1878 workspace: WeakEntity<Workspace>,
1879}
1880
1881const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant";
1882
1883impl CodeActionProvider for AssistantCodeActionProvider {
1884 fn id(&self) -> Arc<str> {
1885 ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
1886 }
1887
1888 fn code_actions(
1889 &self,
1890 buffer: &Entity<Buffer>,
1891 range: Range<text::Anchor>,
1892 _: &mut Window,
1893 cx: &mut App,
1894 ) -> Task<Result<Vec<CodeAction>>> {
1895 if !AgentSettings::get_global(cx).enabled(cx) {
1896 return Task::ready(Ok(Vec::new()));
1897 }
1898
1899 let snapshot = buffer.read(cx).snapshot();
1900 let mut range = range.to_point(&snapshot);
1901
1902 // Expand the range to line boundaries.
1903 range.start.column = 0;
1904 range.end.column = snapshot.line_len(range.end.row);
1905
1906 let mut has_diagnostics = false;
1907 for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
1908 range.start = cmp::min(range.start, diagnostic.range.start);
1909 range.end = cmp::max(range.end, diagnostic.range.end);
1910 has_diagnostics = true;
1911 }
1912 if has_diagnostics {
1913 let symbols_containing_start = snapshot.symbols_containing(range.start, None);
1914 if let Some(symbol) = symbols_containing_start.last() {
1915 range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1916 range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1917 }
1918 let symbols_containing_end = snapshot.symbols_containing(range.end, None);
1919 if let Some(symbol) = symbols_containing_end.last() {
1920 range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
1921 range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
1922 }
1923
1924 Task::ready(Ok(vec![CodeAction {
1925 server_id: language::LanguageServerId(0),
1926 range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
1927 lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
1928 title: "Fix with Assistant".into(),
1929 ..Default::default()
1930 })),
1931 resolved: true,
1932 }]))
1933 } else {
1934 Task::ready(Ok(Vec::new()))
1935 }
1936 }
1937
1938 fn apply_code_action(
1939 &self,
1940 buffer: Entity<Buffer>,
1941 action: CodeAction,
1942 excerpt_id: ExcerptId,
1943 _push_to_history: bool,
1944 window: &mut Window,
1945 cx: &mut App,
1946 ) -> Task<Result<ProjectTransaction>> {
1947 let editor = self.editor.clone();
1948 let workspace = self.workspace.clone();
1949 let prompt_store = PromptStore::global(cx);
1950 window.spawn(cx, async move |cx| {
1951 let workspace = workspace.upgrade().context("workspace was released")?;
1952 let (thread_store, history) = cx.update(|_window, cx| {
1953 let panel = workspace
1954 .read(cx)
1955 .panel::<AgentPanel>(cx)
1956 .context("missing agent panel")?
1957 .read(cx);
1958
1959 let history = panel
1960 .connection_store()
1961 .read(cx)
1962 .entry(&crate::Agent::NativeAgent)
1963 .and_then(|e| e.read(cx).history())
1964 .map(|h| h.downgrade());
1965
1966 anyhow::Ok((panel.thread_store().clone(), history))
1967 })??;
1968 let editor = editor.upgrade().context("editor was released")?;
1969 let range = editor
1970 .update(cx, |editor, cx| {
1971 editor.buffer().update(cx, |multibuffer, cx| {
1972 let buffer = buffer.read(cx);
1973 let multibuffer_snapshot = multibuffer.read(cx);
1974
1975 let old_context_range =
1976 multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
1977 let mut new_context_range = old_context_range.clone();
1978 if action
1979 .range
1980 .start
1981 .cmp(&old_context_range.start, buffer)
1982 .is_lt()
1983 {
1984 new_context_range.start = action.range.start;
1985 }
1986 if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
1987 new_context_range.end = action.range.end;
1988 }
1989 drop(multibuffer_snapshot);
1990
1991 if new_context_range != old_context_range {
1992 multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
1993 }
1994
1995 let multibuffer_snapshot = multibuffer.read(cx);
1996 multibuffer_snapshot.anchor_range_in_excerpt(excerpt_id, action.range)
1997 })
1998 })
1999 .context("invalid range")?;
2000
2001 let prompt_store = prompt_store.await.ok();
2002 cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
2003 let assist_id = assistant.suggest_assist(
2004 &editor,
2005 range,
2006 "Fix Diagnostics".into(),
2007 None,
2008 true,
2009 workspace,
2010 thread_store,
2011 prompt_store,
2012 history,
2013 window,
2014 cx,
2015 );
2016 assistant.start_assist(assist_id, window, cx);
2017 })?;
2018
2019 Ok(ProjectTransaction::default())
2020 })
2021 }
2022}
2023
2024fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
2025 ranges.sort_unstable_by(|a, b| {
2026 a.start
2027 .cmp(&b.start, buffer)
2028 .then_with(|| b.end.cmp(&a.end, buffer))
2029 });
2030
2031 let mut ix = 0;
2032 while ix + 1 < ranges.len() {
2033 let b = ranges[ix + 1].clone();
2034 let a = &mut ranges[ix];
2035 if a.end.cmp(&b.start, buffer).is_gt() {
2036 if a.end.cmp(&b.end, buffer).is_lt() {
2037 a.end = b.end;
2038 }
2039 ranges.remove(ix + 1);
2040 } else {
2041 ix += 1;
2042 }
2043 }
2044}
2045
2046#[cfg(all(test, feature = "unit-eval"))]
2047pub mod evals {
2048 use crate::InlineAssistant;
2049 use agent::ThreadStore;
2050 use client::{Client, UserStore};
2051 use editor::{Editor, MultiBuffer, MultiBufferOffset};
2052 use eval_utils::{EvalOutput, NoProcessor};
2053 use fs::FakeFs;
2054 use futures::channel::mpsc;
2055 use gpui::{AppContext, TestAppContext, UpdateGlobal as _};
2056 use language::Buffer;
2057 use language_model::{LanguageModelRegistry, SelectedModel};
2058 use project::Project;
2059 use prompt_store::PromptBuilder;
2060 use smol::stream::StreamExt as _;
2061 use std::str::FromStr;
2062 use std::sync::Arc;
2063 use util::test::marked_text_ranges;
2064 use workspace::Workspace;
2065
2066 #[derive(Debug)]
2067 enum InlineAssistantOutput {
2068 Success {
2069 completion: Option<String>,
2070 description: Option<String>,
2071 full_buffer_text: String,
2072 },
2073 Failure {
2074 failure: String,
2075 },
2076 // These fields are used for logging
2077 #[allow(unused)]
2078 Malformed {
2079 completion: Option<String>,
2080 description: Option<String>,
2081 failure: Option<String>,
2082 },
2083 }
2084
2085 fn run_inline_assistant_test<SetupF, TestF>(
2086 base_buffer: String,
2087 prompt: String,
2088 setup: SetupF,
2089 test: TestF,
2090 cx: &mut TestAppContext,
2091 ) -> InlineAssistantOutput
2092 where
2093 SetupF: FnOnce(&mut gpui::VisualTestContext),
2094 TestF: FnOnce(&mut gpui::VisualTestContext),
2095 {
2096 let fs = FakeFs::new(cx.executor());
2097 let app_state = cx.update(|cx| workspace::AppState::test(cx));
2098 let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
2099 let http = Arc::new(reqwest_client::ReqwestClient::user_agent("agent tests").unwrap());
2100 let client = cx.update(|cx| {
2101 cx.set_http_client(http);
2102 Client::production(cx)
2103 });
2104 let mut inline_assistant = InlineAssistant::new(fs.clone(), prompt_builder);
2105
2106 let (tx, mut completion_rx) = mpsc::unbounded();
2107 inline_assistant.set_completion_receiver(tx);
2108
2109 // Initialize settings and client
2110 cx.update(|cx| {
2111 gpui_tokio::init(cx);
2112 settings::init(cx);
2113 client::init(&client, cx);
2114 workspace::init(app_state.clone(), cx);
2115 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2116 language_model::init(user_store.clone(), client.clone(), cx);
2117 language_models::init(user_store, client.clone(), cx);
2118
2119 cx.set_global(inline_assistant);
2120 });
2121
2122 let foreground_executor = cx.foreground_executor().clone();
2123 let project =
2124 foreground_executor.block_test(async { Project::test(fs.clone(), [], cx).await });
2125
2126 // Create workspace with window
2127 let (workspace, cx) = cx.add_window_view(|window, cx| {
2128 window.activate_window();
2129 Workspace::new(None, project.clone(), app_state.clone(), window, cx)
2130 });
2131
2132 setup(cx);
2133
2134 let (_editor, buffer) = cx.update(|window, cx| {
2135 let buffer = cx.new(|cx| Buffer::local("", cx));
2136 let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2137 let editor = cx.new(|cx| Editor::for_multibuffer(multibuffer, None, window, cx));
2138 editor.update(cx, |editor, cx| {
2139 let (unmarked_text, selection_ranges) = marked_text_ranges(&base_buffer, true);
2140 editor.set_text(unmarked_text, window, cx);
2141 editor.change_selections(Default::default(), window, cx, |s| {
2142 s.select_ranges(
2143 selection_ranges.into_iter().map(|range| {
2144 MultiBufferOffset(range.start)..MultiBufferOffset(range.end)
2145 }),
2146 )
2147 })
2148 });
2149
2150 let thread_store = cx.new(|cx| ThreadStore::new(cx));
2151
2152 // Add editor to workspace
2153 workspace.update(cx, |workspace, cx| {
2154 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
2155 });
2156
2157 // Call assist method
2158 InlineAssistant::update_global(cx, |inline_assistant, cx| {
2159 let assist_id = inline_assistant
2160 .assist(
2161 &editor,
2162 workspace.downgrade(),
2163 project.downgrade(),
2164 thread_store,
2165 None,
2166 None,
2167 Some(prompt),
2168 window,
2169 cx,
2170 )
2171 .unwrap();
2172
2173 inline_assistant.start_assist(assist_id, window, cx);
2174 });
2175
2176 (editor, buffer)
2177 });
2178
2179 cx.run_until_parked();
2180
2181 test(cx);
2182
2183 let assist_id = foreground_executor
2184 .block_test(async { completion_rx.next().await })
2185 .unwrap()
2186 .unwrap();
2187
2188 let (completion, description, failure) = cx.update(|_, cx| {
2189 InlineAssistant::update_global(cx, |inline_assistant, cx| {
2190 let codegen = inline_assistant.get_codegen(assist_id, cx).unwrap();
2191
2192 let completion = codegen.read(cx).current_completion();
2193 let description = codegen.read(cx).current_description();
2194 let failure = codegen.read(cx).current_failure();
2195
2196 (completion, description, failure)
2197 })
2198 });
2199
2200 if failure.is_some() && (completion.is_some() || description.is_some()) {
2201 InlineAssistantOutput::Malformed {
2202 completion,
2203 description,
2204 failure,
2205 }
2206 } else if let Some(failure) = failure {
2207 InlineAssistantOutput::Failure { failure }
2208 } else {
2209 InlineAssistantOutput::Success {
2210 completion,
2211 description,
2212 full_buffer_text: buffer.read_with(cx, |buffer, _| buffer.text()),
2213 }
2214 }
2215 }
2216
2217 #[test]
2218 #[cfg_attr(not(feature = "unit-eval"), ignore)]
2219 fn eval_single_cursor_edit() {
2220 run_eval(
2221 20,
2222 1.0,
2223 "Rename this variable to buffer_text".to_string(),
2224 indoc::indoc! {"
2225 struct EvalExampleStruct {
2226 text: Strˇing,
2227 prompt: String,
2228 }
2229 "}
2230 .to_string(),
2231 exact_buffer_match(indoc::indoc! {"
2232 struct EvalExampleStruct {
2233 buffer_text: String,
2234 prompt: String,
2235 }
2236 "}),
2237 );
2238 }
2239
2240 #[test]
2241 #[cfg_attr(not(feature = "unit-eval"), ignore)]
2242 fn eval_cant_do() {
2243 run_eval(
2244 20,
2245 0.95,
2246 "Rename the struct to EvalExampleStructNope",
2247 indoc::indoc! {"
2248 struct EvalExampleStruct {
2249 text: Strˇing,
2250 prompt: String,
2251 }
2252 "},
2253 uncertain_output,
2254 );
2255 }
2256
2257 #[test]
2258 #[cfg_attr(not(feature = "unit-eval"), ignore)]
2259 fn eval_unclear() {
2260 run_eval(
2261 20,
2262 0.95,
2263 "Make exactly the change I want you to make",
2264 indoc::indoc! {"
2265 struct EvalExampleStruct {
2266 text: Strˇing,
2267 prompt: String,
2268 }
2269 "},
2270 uncertain_output,
2271 );
2272 }
2273
2274 #[test]
2275 #[cfg_attr(not(feature = "unit-eval"), ignore)]
2276 fn eval_empty_buffer() {
2277 run_eval(
2278 20,
2279 1.0,
2280 "Write a Python hello, world program".to_string(),
2281 "ˇ".to_string(),
2282 |output| match output {
2283 InlineAssistantOutput::Success {
2284 full_buffer_text, ..
2285 } => {
2286 if full_buffer_text.is_empty() {
2287 EvalOutput::failed("expected some output".to_string())
2288 } else {
2289 EvalOutput::passed(format!("Produced {full_buffer_text}"))
2290 }
2291 }
2292 o @ InlineAssistantOutput::Failure { .. } => EvalOutput::failed(format!(
2293 "Assistant output does not match expected output: {:?}",
2294 o
2295 )),
2296 o @ InlineAssistantOutput::Malformed { .. } => EvalOutput::failed(format!(
2297 "Assistant output does not match expected output: {:?}",
2298 o
2299 )),
2300 },
2301 );
2302 }
2303
2304 fn run_eval(
2305 iterations: usize,
2306 expected_pass_ratio: f32,
2307 prompt: impl Into<String>,
2308 buffer: impl Into<String>,
2309 judge: impl Fn(InlineAssistantOutput) -> eval_utils::EvalOutput<()> + Send + Sync + 'static,
2310 ) {
2311 let buffer = buffer.into();
2312 let prompt = prompt.into();
2313
2314 eval_utils::eval(iterations, expected_pass_ratio, NoProcessor, move || {
2315 let dispatcher = gpui::TestDispatcher::new(rand::random());
2316 let mut cx = TestAppContext::build(dispatcher, None);
2317 cx.skip_drawing();
2318
2319 let output = run_inline_assistant_test(
2320 buffer.clone(),
2321 prompt.clone(),
2322 |cx| {
2323 // Reconfigure to use a real model instead of the fake one
2324 let model_name = std::env::var("ZED_AGENT_MODEL")
2325 .unwrap_or("anthropic/claude-sonnet-4-latest".into());
2326
2327 let selected_model = SelectedModel::from_str(&model_name)
2328 .expect("Invalid model format. Use 'provider/model-id'");
2329
2330 log::info!("Selected model: {selected_model:?}");
2331
2332 cx.update(|_, cx| {
2333 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
2334 registry.select_inline_assistant_model(Some(&selected_model), cx);
2335 });
2336 });
2337 },
2338 |_cx| {
2339 log::info!("Waiting for actual response from the LLM...");
2340 },
2341 &mut cx,
2342 );
2343
2344 cx.quit();
2345
2346 judge(output)
2347 });
2348 }
2349
2350 fn uncertain_output(output: InlineAssistantOutput) -> EvalOutput<()> {
2351 match &output {
2352 o @ InlineAssistantOutput::Success {
2353 completion,
2354 description,
2355 ..
2356 } => {
2357 if description.is_some() && completion.is_none() {
2358 EvalOutput::passed(format!(
2359 "Assistant produced no completion, but a description:\n{}",
2360 description.as_ref().unwrap()
2361 ))
2362 } else {
2363 EvalOutput::failed(format!("Assistant produced a completion:\n{:?}", o))
2364 }
2365 }
2366 InlineAssistantOutput::Failure {
2367 failure: error_message,
2368 } => EvalOutput::passed(format!(
2369 "Assistant produced a failure message: {}",
2370 error_message
2371 )),
2372 o @ InlineAssistantOutput::Malformed { .. } => {
2373 EvalOutput::failed(format!("Assistant produced a malformed response:\n{:?}", o))
2374 }
2375 }
2376 }
2377
2378 fn exact_buffer_match(
2379 correct_output: impl Into<String>,
2380 ) -> impl Fn(InlineAssistantOutput) -> EvalOutput<()> {
2381 let correct_output = correct_output.into();
2382 move |output| match output {
2383 InlineAssistantOutput::Success {
2384 description,
2385 full_buffer_text,
2386 ..
2387 } => {
2388 if full_buffer_text == correct_output && description.is_none() {
2389 EvalOutput::passed("Assistant output matches")
2390 } else if full_buffer_text == correct_output {
2391 EvalOutput::failed(format!(
2392 "Assistant output produced an unescessary description description:\n{:?}",
2393 description
2394 ))
2395 } else {
2396 EvalOutput::failed(format!(
2397 "Assistant output does not match expected output:\n{:?}\ndescription:\n{:?}",
2398 full_buffer_text, description
2399 ))
2400 }
2401 }
2402 o @ InlineAssistantOutput::Failure { .. } => EvalOutput::failed(format!(
2403 "Assistant output does not match expected output: {:?}",
2404 o
2405 )),
2406 o @ InlineAssistantOutput::Malformed { .. } => EvalOutput::failed(format!(
2407 "Assistant output does not match expected output: {:?}",
2408 o
2409 )),
2410 }
2411 }
2412}