assistant2.rs

  1mod assistant_settings;
  2mod completion_provider;
  3pub mod tools;
  4
  5use anyhow::{Context, Result};
  6use assistant_tooling::{ToolFunctionCall, ToolRegistry};
  7use client::{proto, Client};
  8use completion_provider::*;
  9use editor::Editor;
 10use feature_flags::FeatureFlagAppExt as _;
 11use futures::{channel::oneshot, future::join_all, Future, FutureExt, StreamExt};
 12use gpui::{
 13    list, prelude::*, AnyElement, AppContext, AsyncWindowContext, EventEmitter, FocusHandle,
 14    FocusableView, Global, ListAlignment, ListState, Model, Render, Task, View, WeakView,
 15};
 16use language::{language_settings::SoftWrap, LanguageRegistry};
 17use open_ai::{FunctionContent, ToolCall, ToolCallContent};
 18use project::Fs;
 19use rich_text::RichText;
 20use semantic_index::{CloudEmbeddingProvider, ProjectIndex, SemanticIndex};
 21use serde::Deserialize;
 22use settings::Settings;
 23use std::{cmp, sync::Arc};
 24use theme::ThemeSettings;
 25use tools::ProjectIndexTool;
 26use ui::{popover_menu, prelude::*, ButtonLike, CollapsibleContainer, Color, ContextMenu, Tooltip};
 27use util::{paths::EMBEDDINGS_DIR, ResultExt};
 28use workspace::{
 29    dock::{DockPosition, Panel, PanelEvent},
 30    Workspace,
 31};
 32
 33pub use assistant_settings::AssistantSettings;
 34
 35const MAX_COMPLETION_CALLS_PER_SUBMISSION: usize = 5;
 36
 37#[derive(Eq, PartialEq, Copy, Clone, Deserialize)]
 38pub struct Submit(SubmitMode);
 39
 40/// There are multiple different ways to submit a model request, represented by this enum.
 41#[derive(Eq, PartialEq, Copy, Clone, Deserialize)]
 42pub enum SubmitMode {
 43    /// Only include the conversation.
 44    Simple,
 45    /// Send the current file as context.
 46    CurrentFile,
 47    /// Search the codebase and send relevant excerpts.
 48    Codebase,
 49}
 50
 51gpui::actions!(assistant2, [Cancel, ToggleFocus]);
 52gpui::impl_actions!(assistant2, [Submit]);
 53
 54pub fn init(client: Arc<Client>, cx: &mut AppContext) {
 55    AssistantSettings::register(cx);
 56
 57    cx.spawn(|mut cx| {
 58        let client = client.clone();
 59        async move {
 60            let embedding_provider = CloudEmbeddingProvider::new(client.clone());
 61            let semantic_index = SemanticIndex::new(
 62                EMBEDDINGS_DIR.join("semantic-index-db.0.mdb"),
 63                Arc::new(embedding_provider),
 64                &mut cx,
 65            )
 66            .await?;
 67            cx.update(|cx| cx.set_global(semantic_index))
 68        }
 69    })
 70    .detach();
 71
 72    cx.set_global(CompletionProvider::new(CloudCompletionProvider::new(
 73        client,
 74    )));
 75
 76    cx.observe_new_views(
 77        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
 78            workspace.register_action(|workspace, _: &ToggleFocus, cx| {
 79                workspace.toggle_panel_focus::<AssistantPanel>(cx);
 80            });
 81        },
 82    )
 83    .detach();
 84}
 85
 86pub fn enabled(cx: &AppContext) -> bool {
 87    cx.is_staff()
 88}
 89
 90pub struct AssistantPanel {
 91    chat: View<AssistantChat>,
 92    width: Option<Pixels>,
 93}
 94
 95impl AssistantPanel {
 96    pub fn load(
 97        workspace: WeakView<Workspace>,
 98        cx: AsyncWindowContext,
 99    ) -> Task<Result<View<Self>>> {
100        cx.spawn(|mut cx| async move {
101            let (app_state, project) = workspace.update(&mut cx, |workspace, _| {
102                (workspace.app_state().clone(), workspace.project().clone())
103            })?;
104
105            cx.new_view(|cx| {
106                // todo!("this will panic if the semantic index failed to load or has not loaded yet")
107                let project_index = cx.update_global(|semantic_index: &mut SemanticIndex, cx| {
108                    semantic_index.project_index(project.clone(), cx)
109                });
110
111                let mut tool_registry = ToolRegistry::new();
112                tool_registry
113                    .register(ProjectIndexTool::new(
114                        project_index.clone(),
115                        app_state.fs.clone(),
116                    ))
117                    .context("failed to register ProjectIndexTool")
118                    .log_err();
119
120                let tool_registry = Arc::new(tool_registry);
121
122                Self::new(app_state.languages.clone(), tool_registry, cx)
123            })
124        })
125    }
126
127    pub fn new(
128        language_registry: Arc<LanguageRegistry>,
129        tool_registry: Arc<ToolRegistry>,
130        cx: &mut ViewContext<Self>,
131    ) -> Self {
132        let chat = cx.new_view(|cx| {
133            AssistantChat::new(language_registry.clone(), tool_registry.clone(), cx)
134        });
135
136        Self { width: None, chat }
137    }
138}
139
140impl Render for AssistantPanel {
141    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
142        div()
143            .size_full()
144            .v_flex()
145            .p_2()
146            .bg(cx.theme().colors().background)
147            .child(self.chat.clone())
148    }
149}
150
151impl Panel for AssistantPanel {
152    fn persistent_name() -> &'static str {
153        "AssistantPanelv2"
154    }
155
156    fn position(&self, _cx: &WindowContext) -> workspace::dock::DockPosition {
157        // todo!("Add a setting / use assistant settings")
158        DockPosition::Right
159    }
160
161    fn position_is_valid(&self, position: workspace::dock::DockPosition) -> bool {
162        matches!(position, DockPosition::Right)
163    }
164
165    fn set_position(&mut self, _: workspace::dock::DockPosition, _: &mut ViewContext<Self>) {
166        // Do nothing until we have a setting for this
167    }
168
169    fn size(&self, _cx: &WindowContext) -> Pixels {
170        self.width.unwrap_or(px(400.))
171    }
172
173    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
174        self.width = size;
175        cx.notify();
176    }
177
178    fn icon(&self, _cx: &WindowContext) -> Option<ui::IconName> {
179        Some(IconName::Ai)
180    }
181
182    fn icon_tooltip(&self, _: &WindowContext) -> Option<&'static str> {
183        Some("Assistant Panel ✨")
184    }
185
186    fn toggle_action(&self) -> Box<dyn gpui::Action> {
187        Box::new(ToggleFocus)
188    }
189}
190
191impl EventEmitter<PanelEvent> for AssistantPanel {}
192
193impl FocusableView for AssistantPanel {
194    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
195        self.chat
196            .read(cx)
197            .messages
198            .iter()
199            .rev()
200            .find_map(|msg| msg.focus_handle(cx))
201            .expect("no user message in chat")
202    }
203}
204
205struct AssistantChat {
206    model: String,
207    messages: Vec<ChatMessage>,
208    list_state: ListState,
209    language_registry: Arc<LanguageRegistry>,
210    next_message_id: MessageId,
211    pending_completion: Option<Task<()>>,
212    tool_registry: Arc<ToolRegistry>,
213}
214
215impl AssistantChat {
216    fn new(
217        language_registry: Arc<LanguageRegistry>,
218        tool_registry: Arc<ToolRegistry>,
219        cx: &mut ViewContext<Self>,
220    ) -> Self {
221        let model = CompletionProvider::get(cx).default_model();
222        let view = cx.view().downgrade();
223        let list_state = ListState::new(
224            0,
225            ListAlignment::Bottom,
226            px(1024.),
227            move |ix, cx: &mut WindowContext| {
228                view.update(cx, |this, cx| this.render_message(ix, cx))
229                    .unwrap()
230            },
231        );
232
233        let mut this = Self {
234            model,
235            messages: Vec::new(),
236            list_state,
237            language_registry,
238            next_message_id: MessageId(0),
239            pending_completion: None,
240            tool_registry,
241        };
242        this.push_new_user_message(true, cx);
243        this
244    }
245
246    fn focused_message_id(&self, cx: &WindowContext) -> Option<MessageId> {
247        self.messages.iter().find_map(|message| match message {
248            ChatMessage::User(message) => message
249                .body
250                .focus_handle(cx)
251                .contains_focused(cx)
252                .then_some(message.id),
253            ChatMessage::Assistant(_) => None,
254        })
255    }
256
257    fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
258        if self.pending_completion.take().is_none() {
259            cx.propagate();
260            return;
261        }
262
263        if let Some(ChatMessage::Assistant(message)) = self.messages.last() {
264            if message.body.text.is_empty() {
265                self.pop_message(cx);
266            } else {
267                self.push_new_user_message(false, cx);
268            }
269        }
270    }
271
272    fn submit(&mut self, Submit(mode): &Submit, cx: &mut ViewContext<Self>) {
273        let Some(focused_message_id) = self.focused_message_id(cx) else {
274            log::error!("unexpected state: no user message editor is focused.");
275            return;
276        };
277
278        self.truncate_messages(focused_message_id, cx);
279
280        let mode = *mode;
281        self.pending_completion = Some(cx.spawn(move |this, mut cx| async move {
282            Self::request_completion(
283                this.clone(),
284                mode,
285                MAX_COMPLETION_CALLS_PER_SUBMISSION,
286                &mut cx,
287            )
288            .await
289            .log_err();
290
291            this.update(&mut cx, |this, cx| {
292                let focus = this
293                    .user_message(focused_message_id)
294                    .body
295                    .focus_handle(cx)
296                    .contains_focused(cx);
297                this.push_new_user_message(focus, cx);
298                this.pending_completion = None;
299            })
300            .context("Failed to push new user message")
301            .log_err();
302        }));
303    }
304
305    async fn request_completion(
306        this: WeakView<Self>,
307        mode: SubmitMode,
308        limit: usize,
309        cx: &mut AsyncWindowContext,
310    ) -> Result<()> {
311        let mut call_count = 0;
312        loop {
313            let complete = async {
314                let completion = this.update(cx, |this, cx| {
315                    this.push_new_assistant_message(cx);
316
317                    let definitions = if call_count < limit && matches!(mode, SubmitMode::Codebase)
318                    {
319                        this.tool_registry.definitions()
320                    } else {
321                        &[]
322                    };
323                    call_count += 1;
324
325                    CompletionProvider::get(cx).complete(
326                        this.model.clone(),
327                        this.completion_messages(cx),
328                        Vec::new(),
329                        1.0,
330                        definitions,
331                    )
332                });
333
334                let mut stream = completion?.await?;
335                let mut body = String::new();
336                while let Some(delta) = stream.next().await {
337                    let delta = delta?;
338                    this.update(cx, |this, cx| {
339                        if let Some(ChatMessage::Assistant(AssistantMessage {
340                            body: message_body,
341                            tool_calls: message_tool_calls,
342                            ..
343                        })) = this.messages.last_mut()
344                        {
345                            if let Some(content) = &delta.content {
346                                body.push_str(content);
347                            }
348
349                            for tool_call in delta.tool_calls {
350                                let index = tool_call.index as usize;
351                                if index >= message_tool_calls.len() {
352                                    message_tool_calls.resize_with(index + 1, Default::default);
353                                }
354                                let call = &mut message_tool_calls[index];
355
356                                if let Some(id) = &tool_call.id {
357                                    call.id.push_str(id);
358                                }
359
360                                match tool_call.variant {
361                                    Some(proto::tool_call_delta::Variant::Function(tool_call)) => {
362                                        if let Some(name) = &tool_call.name {
363                                            call.name.push_str(name);
364                                        }
365                                        if let Some(arguments) = &tool_call.arguments {
366                                            call.arguments.push_str(arguments);
367                                        }
368                                    }
369                                    None => {}
370                                }
371                            }
372
373                            *message_body =
374                                RichText::new(body.clone(), &[], &this.language_registry);
375                            cx.notify();
376                        } else {
377                            unreachable!()
378                        }
379                    })?;
380                }
381
382                anyhow::Ok(())
383            }
384            .await;
385
386            let mut tool_tasks = Vec::new();
387            this.update(cx, |this, cx| {
388                if let Some(ChatMessage::Assistant(AssistantMessage {
389                    error: message_error,
390                    tool_calls,
391                    ..
392                })) = this.messages.last_mut()
393                {
394                    if let Err(error) = complete {
395                        message_error.replace(SharedString::from(error.to_string()));
396                        cx.notify();
397                    } else {
398                        for tool_call in tool_calls.iter() {
399                            tool_tasks.push(this.tool_registry.call(tool_call, cx));
400                        }
401                    }
402                }
403            })?;
404
405            if tool_tasks.is_empty() {
406                return Ok(());
407            }
408
409            let tools = join_all(tool_tasks.into_iter()).await;
410            this.update(cx, |this, cx| {
411                if let Some(ChatMessage::Assistant(AssistantMessage { tool_calls, .. })) =
412                    this.messages.last_mut()
413                {
414                    *tool_calls = tools;
415                    cx.notify();
416                }
417            })?;
418        }
419    }
420
421    fn user_message(&mut self, message_id: MessageId) -> &mut UserMessage {
422        self.messages
423            .iter_mut()
424            .find_map(|message| match message {
425                ChatMessage::User(user_message) if user_message.id == message_id => {
426                    Some(user_message)
427                }
428                _ => None,
429            })
430            .expect("User message not found")
431    }
432
433    fn push_new_user_message(&mut self, focus: bool, cx: &mut ViewContext<Self>) {
434        let id = self.next_message_id.post_inc();
435        let body = cx.new_view(|cx| {
436            let mut editor = Editor::auto_height(80, cx);
437            editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
438            if focus {
439                cx.focus_self();
440            }
441            editor
442        });
443        let message = ChatMessage::User(UserMessage {
444            id,
445            body,
446            contexts: Vec::new(),
447        });
448        self.push_message(message, cx);
449    }
450
451    fn push_new_assistant_message(&mut self, cx: &mut ViewContext<Self>) {
452        let message = ChatMessage::Assistant(AssistantMessage {
453            id: self.next_message_id.post_inc(),
454            body: RichText::default(),
455            tool_calls: Vec::new(),
456            error: None,
457        });
458        self.push_message(message, cx);
459    }
460
461    fn push_message(&mut self, message: ChatMessage, cx: &mut ViewContext<Self>) {
462        let old_len = self.messages.len();
463        let focus_handle = Some(message.focus_handle(cx));
464        self.messages.push(message);
465        self.list_state
466            .splice_focusable(old_len..old_len, focus_handle);
467        cx.notify();
468    }
469
470    fn pop_message(&mut self, cx: &mut ViewContext<Self>) {
471        if self.messages.is_empty() {
472            return;
473        }
474
475        self.messages.pop();
476        self.list_state
477            .splice(self.messages.len()..self.messages.len() + 1, 0);
478        cx.notify();
479    }
480
481    fn truncate_messages(&mut self, last_message_id: MessageId, cx: &mut ViewContext<Self>) {
482        if let Some(index) = self.messages.iter().position(|message| match message {
483            ChatMessage::User(message) => message.id == last_message_id,
484            ChatMessage::Assistant(message) => message.id == last_message_id,
485        }) {
486            self.list_state.splice(index + 1..self.messages.len(), 0);
487            self.messages.truncate(index + 1);
488            cx.notify();
489        }
490    }
491
492    fn render_error(
493        &self,
494        error: Option<SharedString>,
495        _ix: usize,
496        cx: &mut ViewContext<Self>,
497    ) -> AnyElement {
498        let theme = cx.theme();
499
500        if let Some(error) = error {
501            div()
502                .py_1()
503                .px_2()
504                .neg_mx_1()
505                .rounded_md()
506                .border()
507                .border_color(theme.status().error_border)
508                // .bg(theme.status().error_background)
509                .text_color(theme.status().error)
510                .child(error.clone())
511                .into_any_element()
512        } else {
513            div().into_any_element()
514        }
515    }
516
517    fn render_message(&self, ix: usize, cx: &mut ViewContext<Self>) -> AnyElement {
518        let is_last = ix == self.messages.len() - 1;
519
520        match &self.messages[ix] {
521            ChatMessage::User(UserMessage {
522                body,
523                contexts: _contexts,
524                ..
525            }) => div()
526                .when(!is_last, |element| element.mb_2())
527                .child(div().p_2().child(Label::new("You").color(Color::Default)))
528                .child(
529                    div()
530                        .on_action(cx.listener(Self::submit))
531                        .p_2()
532                        .text_color(cx.theme().colors().editor_foreground)
533                        .font(ThemeSettings::get_global(cx).buffer_font.clone())
534                        .bg(cx.theme().colors().editor_background)
535                        .child(body.clone()), // .children(contexts.iter().map(|context| context.render(cx))),
536                )
537                .into_any(),
538            ChatMessage::Assistant(AssistantMessage {
539                id,
540                body,
541                error,
542                tool_calls,
543                ..
544            }) => {
545                let assistant_body = if body.text.is_empty() && !tool_calls.is_empty() {
546                    div()
547                } else {
548                    div().p_2().child(body.element(ElementId::from(id.0), cx))
549                };
550
551                div()
552                    .when(!is_last, |element| element.mb_2())
553                    .child(
554                        div()
555                            .p_2()
556                            .child(Label::new("Assistant").color(Color::Modified)),
557                    )
558                    .child(assistant_body)
559                    .child(self.render_error(error.clone(), ix, cx))
560                    .children(tool_calls.iter().map(|tool_call| {
561                        let result = &tool_call.result;
562                        let name = tool_call.name.clone();
563                        match result {
564                            Some(result) => div()
565                                .p_2()
566                                .child(result.render(&name, &tool_call.id, cx))
567                                .into_any(),
568                            None => div()
569                                .p_2()
570                                .child(Label::new(name).color(Color::Modified))
571                                .child("Running...")
572                                .into_any(),
573                        }
574                    }))
575                    .into_any()
576            }
577        }
578    }
579
580    fn completion_messages(&self, cx: &WindowContext) -> Vec<CompletionMessage> {
581        let mut completion_messages = Vec::new();
582
583        for message in &self.messages {
584            match message {
585                ChatMessage::User(UserMessage { body, contexts, .. }) => {
586                    // setup context for model
587                    contexts.iter().for_each(|context| {
588                        completion_messages.extend(context.completion_messages(cx))
589                    });
590
591                    // Show user's message last so that the assistant is grounded in the user's request
592                    completion_messages.push(CompletionMessage::User {
593                        content: body.read(cx).text(cx),
594                    });
595                }
596                ChatMessage::Assistant(AssistantMessage {
597                    body, tool_calls, ..
598                }) => {
599                    // In no case do we want to send an empty message. This shouldn't happen, but we might as well
600                    // not break the Chat API if it does.
601                    if body.text.is_empty() && tool_calls.is_empty() {
602                        continue;
603                    }
604
605                    let tool_calls_from_assistant = tool_calls
606                        .iter()
607                        .map(|tool_call| ToolCall {
608                            content: ToolCallContent::Function {
609                                function: FunctionContent {
610                                    name: tool_call.name.clone(),
611                                    arguments: tool_call.arguments.clone(),
612                                },
613                            },
614                            id: tool_call.id.clone(),
615                        })
616                        .collect();
617
618                    completion_messages.push(CompletionMessage::Assistant {
619                        content: Some(body.text.to_string()),
620                        tool_calls: tool_calls_from_assistant,
621                    });
622
623                    for tool_call in tool_calls {
624                        // todo!(): we should not be sending when the tool is still running / has no result
625                        // For now I'm going to have to assume we send an empty string because otherwise
626                        // the Chat API will break -- there is a required message for every tool call by ID
627                        let content = match &tool_call.result {
628                            Some(result) => result.format(&tool_call.name),
629                            None => "".to_string(),
630                        };
631
632                        completion_messages.push(CompletionMessage::Tool {
633                            content,
634                            tool_call_id: tool_call.id.clone(),
635                        });
636                    }
637                }
638            }
639        }
640
641        completion_messages
642    }
643
644    fn render_model_dropdown(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
645        let this = cx.view().downgrade();
646        div().h_flex().justify_end().child(
647            div().w_32().child(
648                popover_menu("user-menu")
649                    .menu(move |cx| {
650                        ContextMenu::build(cx, |mut menu, cx| {
651                            for model in CompletionProvider::get(cx).available_models() {
652                                menu = menu.custom_entry(
653                                    {
654                                        let model = model.clone();
655                                        move |_| Label::new(model.clone()).into_any_element()
656                                    },
657                                    {
658                                        let this = this.clone();
659                                        move |cx| {
660                                            _ = this.update(cx, |this, cx| {
661                                                this.model = model.clone();
662                                                cx.notify();
663                                            });
664                                        }
665                                    },
666                                );
667                            }
668                            menu
669                        })
670                        .into()
671                    })
672                    .trigger(
673                        ButtonLike::new("active-model")
674                            .child(
675                                h_flex()
676                                    .w_full()
677                                    .gap_0p5()
678                                    .child(
679                                        div()
680                                            .overflow_x_hidden()
681                                            .flex_grow()
682                                            .whitespace_nowrap()
683                                            .child(Label::new(self.model.clone())),
684                                    )
685                                    .child(div().child(
686                                        Icon::new(IconName::ChevronDown).color(Color::Muted),
687                                    )),
688                            )
689                            .style(ButtonStyle::Subtle)
690                            .tooltip(move |cx| Tooltip::text("Change Model", cx)),
691                    )
692                    .anchor(gpui::AnchorCorner::TopRight),
693            ),
694        )
695    }
696}
697
698impl Render for AssistantChat {
699    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
700        div()
701            .relative()
702            .flex_1()
703            .v_flex()
704            .key_context("AssistantChat")
705            .on_action(cx.listener(Self::cancel))
706            .text_color(Color::Default.color(cx))
707            .child(self.render_model_dropdown(cx))
708            .child(list(self.list_state.clone()).flex_1())
709    }
710}
711
712#[derive(Copy, Clone, Eq, PartialEq)]
713struct MessageId(usize);
714
715impl MessageId {
716    fn post_inc(&mut self) -> Self {
717        let id = *self;
718        self.0 += 1;
719        id
720    }
721}
722
723enum ChatMessage {
724    User(UserMessage),
725    Assistant(AssistantMessage),
726}
727
728impl ChatMessage {
729    fn focus_handle(&self, cx: &AppContext) -> Option<FocusHandle> {
730        match self {
731            ChatMessage::User(UserMessage { body, .. }) => Some(body.focus_handle(cx)),
732            ChatMessage::Assistant(_) => None,
733        }
734    }
735}
736
737struct UserMessage {
738    id: MessageId,
739    body: View<Editor>,
740    contexts: Vec<AssistantContext>,
741}
742
743struct AssistantMessage {
744    id: MessageId,
745    body: RichText,
746    tool_calls: Vec<ToolFunctionCall>,
747    error: Option<SharedString>,
748}
749
750// Since we're swapping out for direct query usage, we might not need to use this injected context
751// It will be useful though for when the user _definitely_ wants the model to see a specific file,
752// query, error, etc.
753#[allow(dead_code)]
754enum AssistantContext {
755    Codebase(View<CodebaseContext>),
756}
757
758#[allow(dead_code)]
759struct CodebaseExcerpt {
760    element_id: ElementId,
761    path: SharedString,
762    text: SharedString,
763    score: f32,
764    expanded: bool,
765}
766
767impl AssistantContext {
768    #[allow(dead_code)]
769    fn render(&self, _cx: &mut ViewContext<AssistantChat>) -> AnyElement {
770        match self {
771            AssistantContext::Codebase(context) => context.clone().into_any_element(),
772        }
773    }
774
775    fn completion_messages(&self, cx: &WindowContext) -> Vec<CompletionMessage> {
776        match self {
777            AssistantContext::Codebase(context) => context.read(cx).completion_messages(),
778        }
779    }
780}
781
782enum CodebaseContext {
783    Pending { _task: Task<()> },
784    Done(Result<Vec<CodebaseExcerpt>>),
785}
786
787impl CodebaseContext {
788    fn toggle_expanded(&mut self, element_id: ElementId, cx: &mut ViewContext<Self>) {
789        if let CodebaseContext::Done(Ok(excerpts)) = self {
790            if let Some(excerpt) = excerpts
791                .iter_mut()
792                .find(|excerpt| excerpt.element_id == element_id)
793            {
794                excerpt.expanded = !excerpt.expanded;
795                cx.notify();
796            }
797        }
798    }
799}
800
801impl Render for CodebaseContext {
802    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
803        match self {
804            CodebaseContext::Pending { .. } => div()
805                .h_flex()
806                .items_center()
807                .gap_1()
808                .child(Icon::new(IconName::Ai).color(Color::Muted).into_element())
809                .child("Searching codebase..."),
810            CodebaseContext::Done(Ok(excerpts)) => {
811                div()
812                    .v_flex()
813                    .gap_2()
814                    .children(excerpts.iter().map(|excerpt| {
815                        let expanded = excerpt.expanded;
816                        let element_id = excerpt.element_id.clone();
817
818                        CollapsibleContainer::new(element_id.clone(), expanded)
819                            .start_slot(
820                                h_flex()
821                                    .gap_1()
822                                    .child(Icon::new(IconName::File).color(Color::Muted))
823                                    .child(Label::new(excerpt.path.clone()).color(Color::Muted)),
824                            )
825                            .on_click(cx.listener(move |this, _, cx| {
826                                this.toggle_expanded(element_id.clone(), cx);
827                            }))
828                            .child(
829                                div()
830                                    .p_2()
831                                    .rounded_md()
832                                    .bg(cx.theme().colors().editor_background)
833                                    .child(
834                                        excerpt.text.clone(), // todo!(): Show as an editor block
835                                    ),
836                            )
837                    }))
838            }
839            CodebaseContext::Done(Err(error)) => div().child(error.to_string()),
840        }
841    }
842}
843
844impl CodebaseContext {
845    #[allow(dead_code)]
846    fn new(
847        query: impl 'static + Future<Output = Result<String>>,
848        populated: oneshot::Sender<bool>,
849        project_index: Model<ProjectIndex>,
850        fs: Arc<dyn Fs>,
851        cx: &mut ViewContext<Self>,
852    ) -> Self {
853        let query = query.boxed_local();
854        let _task = cx.spawn(|this, mut cx| async move {
855            let result = async {
856                let query = query.await?;
857                let results = this
858                    .update(&mut cx, |_this, cx| {
859                        project_index.read(cx).search(&query, 16, cx)
860                    })?
861                    .await;
862
863                let excerpts = results.into_iter().map(|result| {
864                    let abs_path = result
865                        .worktree
866                        .read_with(&cx, |worktree, _| worktree.abs_path().join(&result.path));
867                    let fs = fs.clone();
868
869                    async move {
870                        let path = result.path.clone();
871                        let text = fs.load(&abs_path?).await?;
872                        // todo!("what should we do with stale ranges?");
873                        let range = cmp::min(result.range.start, text.len())
874                            ..cmp::min(result.range.end, text.len());
875
876                        let text = SharedString::from(text[range].to_string());
877
878                        anyhow::Ok(CodebaseExcerpt {
879                            element_id: ElementId::Name(nanoid::nanoid!().into()),
880                            path: path.to_string_lossy().to_string().into(),
881                            text,
882                            score: result.score,
883                            expanded: false,
884                        })
885                    }
886                });
887
888                anyhow::Ok(
889                    futures::future::join_all(excerpts)
890                        .await
891                        .into_iter()
892                        .filter_map(|result| result.log_err())
893                        .collect(),
894                )
895            }
896            .await;
897
898            this.update(&mut cx, |this, cx| {
899                this.populate(result, populated, cx);
900            })
901            .ok();
902        });
903
904        Self::Pending { _task }
905    }
906
907    #[allow(dead_code)]
908    fn populate(
909        &mut self,
910        result: Result<Vec<CodebaseExcerpt>>,
911        populated: oneshot::Sender<bool>,
912        cx: &mut ViewContext<Self>,
913    ) {
914        let success = result.is_ok();
915        *self = Self::Done(result);
916        populated.send(success).ok();
917        cx.notify();
918    }
919
920    fn completion_messages(&self) -> Vec<CompletionMessage> {
921        // One system message for the whole batch of excerpts:
922
923        // Semantic search results for user query:
924        //
925        // Excerpt from $path:
926        // ~~~
927        // `text`
928        // ~~~
929        //
930        // Excerpt from $path:
931
932        match self {
933            CodebaseContext::Done(Ok(excerpts)) => {
934                if excerpts.is_empty() {
935                    return Vec::new();
936                }
937
938                let mut body = "Semantic search results for user query:\n".to_string();
939
940                for excerpt in excerpts {
941                    body.push_str("Excerpt from ");
942                    body.push_str(excerpt.path.as_ref());
943                    body.push_str(", score ");
944                    body.push_str(&excerpt.score.to_string());
945                    body.push_str(":\n");
946                    body.push_str("~~~\n");
947                    body.push_str(excerpt.text.as_ref());
948                    body.push_str("~~~\n");
949                }
950
951                vec![CompletionMessage::System { content: body }]
952            }
953            _ => vec![],
954        }
955    }
956}