Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T04:08:23.690Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

inline_assistant.rs

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