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