copilot_chat.rs

  1use std::pin::Pin;
  2use std::str::FromStr as _;
  3use std::sync::Arc;
  4
  5use anyhow::{Result, anyhow};
  6use collections::HashMap;
  7use copilot::copilot_chat::{
  8    ChatMessage, ChatMessageContent, ChatMessagePart, CopilotChat, ImageUrl,
  9    Model as CopilotChatModel, ModelVendor, Request as CopilotChatRequest, ResponseEvent, Tool,
 10    ToolCall,
 11};
 12use copilot::{Copilot, Status};
 13use editor::{Editor, EditorElement, EditorStyle};
 14use fs::Fs;
 15use futures::future::BoxFuture;
 16use futures::stream::BoxStream;
 17use futures::{FutureExt, Stream, StreamExt};
 18use gpui::{
 19    Action, Animation, AnimationExt, AnyView, App, AsyncApp, Entity, FontStyle, Render,
 20    Subscription, Task, TextStyle, Transformation, WhiteSpace, percentage, svg,
 21};
 22use language_model::{
 23    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
 24    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
 25    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
 26    LanguageModelRequestMessage, LanguageModelToolChoice, LanguageModelToolResultContent,
 27    LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, RateLimiter, Role,
 28    StopReason,
 29};
 30use settings::{Settings, SettingsStore, update_settings_file};
 31use std::time::Duration;
 32use theme::ThemeSettings;
 33use ui::prelude::*;
 34use util::debug_panic;
 35
 36use crate::{AllLanguageModelSettings, CopilotChatSettingsContent};
 37
 38use super::anthropic::count_anthropic_tokens;
 39use super::google::count_google_tokens;
 40use super::open_ai::count_open_ai_tokens;
 41pub(crate) use copilot::copilot_chat::CopilotChatSettings;
 42
 43const PROVIDER_ID: &str = "copilot_chat";
 44const PROVIDER_NAME: &str = "GitHub Copilot Chat";
 45
 46pub struct CopilotChatLanguageModelProvider {
 47    state: Entity<State>,
 48}
 49
 50pub struct State {
 51    _copilot_chat_subscription: Option<Subscription>,
 52    _settings_subscription: Subscription,
 53}
 54
 55impl State {
 56    fn is_authenticated(&self, cx: &App) -> bool {
 57        CopilotChat::global(cx)
 58            .map(|m| m.read(cx).is_authenticated())
 59            .unwrap_or(false)
 60    }
 61}
 62
 63impl CopilotChatLanguageModelProvider {
 64    pub fn new(cx: &mut App) -> Self {
 65        let state = cx.new(|cx| {
 66            let copilot_chat_subscription = CopilotChat::global(cx)
 67                .map(|copilot_chat| cx.observe(&copilot_chat, |_, _, cx| cx.notify()));
 68            State {
 69                _copilot_chat_subscription: copilot_chat_subscription,
 70                _settings_subscription: cx.observe_global::<SettingsStore>(|_, cx| {
 71                    if let Some(copilot_chat) = CopilotChat::global(cx) {
 72                        let settings = AllLanguageModelSettings::get_global(cx)
 73                            .copilot_chat
 74                            .clone();
 75                        copilot_chat.update(cx, |chat, cx| {
 76                            chat.set_settings(settings, cx);
 77                        });
 78                    }
 79                    cx.notify();
 80                }),
 81            }
 82        });
 83
 84        Self { state }
 85    }
 86
 87    fn create_language_model(&self, model: CopilotChatModel) -> Arc<dyn LanguageModel> {
 88        Arc::new(CopilotChatLanguageModel {
 89            model,
 90            request_limiter: RateLimiter::new(4),
 91        })
 92    }
 93}
 94
 95impl LanguageModelProviderState for CopilotChatLanguageModelProvider {
 96    type ObservableEntity = State;
 97
 98    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
 99        Some(self.state.clone())
100    }
101}
102
103impl LanguageModelProvider for CopilotChatLanguageModelProvider {
104    fn id(&self) -> LanguageModelProviderId {
105        LanguageModelProviderId(PROVIDER_ID.into())
106    }
107
108    fn name(&self) -> LanguageModelProviderName {
109        LanguageModelProviderName(PROVIDER_NAME.into())
110    }
111
112    fn icon(&self) -> IconName {
113        IconName::Copilot
114    }
115
116    fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
117        let models = CopilotChat::global(cx).and_then(|m| m.read(cx).models())?;
118        models
119            .first()
120            .map(|model| self.create_language_model(model.clone()))
121    }
122
123    fn default_fast_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
124        // The default model should be Copilot Chat's 'base model', which is likely a relatively fast
125        // model (e.g. 4o) and a sensible choice when considering premium requests
126        self.default_model(cx)
127    }
128
129    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
130        let Some(models) = CopilotChat::global(cx).and_then(|m| m.read(cx).models()) else {
131            return Vec::new();
132        };
133        models
134            .iter()
135            .map(|model| self.create_language_model(model.clone()))
136            .collect()
137    }
138
139    fn is_authenticated(&self, cx: &App) -> bool {
140        self.state.read(cx).is_authenticated(cx)
141    }
142
143    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
144        if self.is_authenticated(cx) {
145            return Task::ready(Ok(()));
146        };
147
148        let Some(copilot) = Copilot::global(cx) else {
149            return Task::ready( Err(anyhow!(
150                "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
151            ).into()));
152        };
153
154        let err = match copilot.read(cx).status() {
155            Status::Authorized => return Task::ready(Ok(())),
156            Status::Disabled => anyhow!(
157                "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
158            ),
159            Status::Error(err) => anyhow!(format!(
160                "Received the following error while signing into Copilot: {err}"
161            )),
162            Status::Starting { task: _ } => anyhow!(
163                "Copilot is still starting, please wait for Copilot to start then try again"
164            ),
165            Status::Unauthorized => anyhow!(
166                "Unable to authorize with Copilot. Please make sure that you have an active Copilot and Copilot Chat subscription."
167            ),
168            Status::SignedOut { .. } => {
169                anyhow!("You have signed out of Copilot. Please sign in to Copilot and try again.")
170            }
171            Status::SigningIn { prompt: _ } => anyhow!("Still signing into Copilot..."),
172        };
173
174        Task::ready(Err(err.into()))
175    }
176
177    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
178        let state = self.state.clone();
179        cx.new(|cx| ConfigurationView::new(state, window, cx))
180            .into()
181    }
182
183    fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
184        Task::ready(Err(anyhow!(
185            "Signing out of GitHub Copilot Chat is currently not supported."
186        )))
187    }
188}
189
190pub struct CopilotChatLanguageModel {
191    model: CopilotChatModel,
192    request_limiter: RateLimiter,
193}
194
195impl LanguageModel for CopilotChatLanguageModel {
196    fn id(&self) -> LanguageModelId {
197        LanguageModelId::from(self.model.id().to_string())
198    }
199
200    fn name(&self) -> LanguageModelName {
201        LanguageModelName::from(self.model.display_name().to_string())
202    }
203
204    fn provider_id(&self) -> LanguageModelProviderId {
205        LanguageModelProviderId(PROVIDER_ID.into())
206    }
207
208    fn provider_name(&self) -> LanguageModelProviderName {
209        LanguageModelProviderName(PROVIDER_NAME.into())
210    }
211
212    fn supports_tools(&self) -> bool {
213        self.model.supports_tools()
214    }
215
216    fn supports_images(&self) -> bool {
217        self.model.supports_vision()
218    }
219
220    fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
221        match self.model.vendor() {
222            ModelVendor::OpenAI | ModelVendor::Anthropic => {
223                LanguageModelToolSchemaFormat::JsonSchema
224            }
225            ModelVendor::Google => LanguageModelToolSchemaFormat::JsonSchemaSubset,
226        }
227    }
228
229    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
230        match choice {
231            LanguageModelToolChoice::Auto
232            | LanguageModelToolChoice::Any
233            | LanguageModelToolChoice::None => self.supports_tools(),
234        }
235    }
236
237    fn telemetry_id(&self) -> String {
238        format!("copilot_chat/{}", self.model.id())
239    }
240
241    fn max_token_count(&self) -> usize {
242        self.model.max_token_count()
243    }
244
245    fn count_tokens(
246        &self,
247        request: LanguageModelRequest,
248        cx: &App,
249    ) -> BoxFuture<'static, Result<usize>> {
250        match self.model.vendor() {
251            ModelVendor::Anthropic => count_anthropic_tokens(request, cx),
252            ModelVendor::Google => count_google_tokens(request, cx),
253            ModelVendor::OpenAI => {
254                let model = open_ai::Model::from_id(self.model.id()).unwrap_or_default();
255                count_open_ai_tokens(request, model, cx)
256            }
257        }
258    }
259
260    fn stream_completion(
261        &self,
262        request: LanguageModelRequest,
263        cx: &AsyncApp,
264    ) -> BoxFuture<
265        'static,
266        Result<
267            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
268        >,
269    > {
270        if let Some(message) = request.messages.last() {
271            if message.contents_empty() {
272                const EMPTY_PROMPT_MSG: &str =
273                    "Empty prompts aren't allowed. Please provide a non-empty prompt.";
274                return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG))).boxed();
275            }
276
277            // Copilot Chat has a restriction that the final message must be from the user.
278            // While their API does return an error message for this, we can catch it earlier
279            // and provide a more helpful error message.
280            if !matches!(message.role, Role::User) {
281                const USER_ROLE_MSG: &str = "The final message must be from the user. To provide a system prompt, you must provide the system prompt followed by a user prompt.";
282                return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG))).boxed();
283            }
284        }
285
286        let copilot_request = match into_copilot_chat(&self.model, request) {
287            Ok(request) => request,
288            Err(err) => return futures::future::ready(Err(err)).boxed(),
289        };
290        let is_streaming = copilot_request.stream;
291
292        let request_limiter = self.request_limiter.clone();
293        let future = cx.spawn(async move |cx| {
294            let request = CopilotChat::stream_completion(copilot_request, cx.clone());
295            request_limiter
296                .stream(async move {
297                    let response = request.await?;
298                    Ok(map_to_language_model_completion_events(
299                        response,
300                        is_streaming,
301                    ))
302                })
303                .await
304        });
305        async move { Ok(future.await?.boxed()) }.boxed()
306    }
307}
308
309pub fn map_to_language_model_completion_events(
310    events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
311    is_streaming: bool,
312) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
313    #[derive(Default)]
314    struct RawToolCall {
315        id: String,
316        name: String,
317        arguments: String,
318    }
319
320    struct State {
321        events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
322        tool_calls_by_index: HashMap<usize, RawToolCall>,
323    }
324
325    futures::stream::unfold(
326        State {
327            events,
328            tool_calls_by_index: HashMap::default(),
329        },
330        move |mut state| async move {
331            if let Some(event) = state.events.next().await {
332                match event {
333                    Ok(event) => {
334                        let Some(choice) = event.choices.first() else {
335                            return Some((
336                                vec![Err(anyhow!("Response contained no choices").into())],
337                                state,
338                            ));
339                        };
340
341                        let delta = if is_streaming {
342                            choice.delta.as_ref()
343                        } else {
344                            choice.message.as_ref()
345                        };
346
347                        let Some(delta) = delta else {
348                            return Some((
349                                vec![Err(anyhow!("Response contained no delta").into())],
350                                state,
351                            ));
352                        };
353
354                        let mut events = Vec::new();
355                        if let Some(content) = delta.content.clone() {
356                            events.push(Ok(LanguageModelCompletionEvent::Text(content)));
357                        }
358
359                        for tool_call in &delta.tool_calls {
360                            let entry = state
361                                .tool_calls_by_index
362                                .entry(tool_call.index)
363                                .or_default();
364
365                            if let Some(tool_id) = tool_call.id.clone() {
366                                entry.id = tool_id;
367                            }
368
369                            if let Some(function) = tool_call.function.as_ref() {
370                                if let Some(name) = function.name.clone() {
371                                    entry.name = name;
372                                }
373
374                                if let Some(arguments) = function.arguments.clone() {
375                                    entry.arguments.push_str(&arguments);
376                                }
377                            }
378                        }
379
380                        match choice.finish_reason.as_deref() {
381                            Some("stop") => {
382                                events.push(Ok(LanguageModelCompletionEvent::Stop(
383                                    StopReason::EndTurn,
384                                )));
385                            }
386                            Some("tool_calls") => {
387                                events.extend(state.tool_calls_by_index.drain().map(
388                                    |(_, tool_call)| {
389                                        // The model can output an empty string
390                                        // to indicate the absence of arguments.
391                                        // When that happens, create an empty
392                                        // object instead.
393                                        let arguments = if tool_call.arguments.is_empty() {
394                                            Ok(serde_json::Value::Object(Default::default()))
395                                        } else {
396                                            serde_json::Value::from_str(&tool_call.arguments)
397                                        };
398                                        match arguments {
399                                            Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
400                                                LanguageModelToolUse {
401                                                    id: tool_call.id.clone().into(),
402                                                    name: tool_call.name.as_str().into(),
403                                                    is_input_complete: true,
404                                                    input,
405                                                    raw_input: tool_call.arguments.clone(),
406                                                },
407                                            )),
408                                            Err(error) => {
409                                                Err(LanguageModelCompletionError::BadInputJson {
410                                                    id: tool_call.id.into(),
411                                                    tool_name: tool_call.name.as_str().into(),
412                                                    raw_input: tool_call.arguments.into(),
413                                                    json_parse_error: error.to_string(),
414                                                })
415                                            }
416                                        }
417                                    },
418                                ));
419
420                                events.push(Ok(LanguageModelCompletionEvent::Stop(
421                                    StopReason::ToolUse,
422                                )));
423                            }
424                            Some(stop_reason) => {
425                                log::error!("Unexpected Copilot Chat stop_reason: {stop_reason:?}");
426                                events.push(Ok(LanguageModelCompletionEvent::Stop(
427                                    StopReason::EndTurn,
428                                )));
429                            }
430                            None => {}
431                        }
432
433                        return Some((events, state));
434                    }
435                    Err(err) => return Some((vec![Err(anyhow!(err).into())], state)),
436                }
437            }
438
439            None
440        },
441    )
442    .flat_map(futures::stream::iter)
443}
444
445fn into_copilot_chat(
446    model: &copilot::copilot_chat::Model,
447    request: LanguageModelRequest,
448) -> Result<CopilotChatRequest> {
449    let mut request_messages: Vec<LanguageModelRequestMessage> = Vec::new();
450    for message in request.messages {
451        if let Some(last_message) = request_messages.last_mut() {
452            if last_message.role == message.role {
453                last_message.content.extend(message.content);
454            } else {
455                request_messages.push(message);
456            }
457        } else {
458            request_messages.push(message);
459        }
460    }
461
462    let mut tool_called = false;
463    let mut messages: Vec<ChatMessage> = Vec::new();
464    for message in request_messages {
465        match message.role {
466            Role::User => {
467                for content in &message.content {
468                    if let MessageContent::ToolResult(tool_result) = content {
469                        let content = match &tool_result.content {
470                            LanguageModelToolResultContent::Text(text) => text.to_string().into(),
471                            LanguageModelToolResultContent::Image(image) => {
472                                if model.supports_vision() {
473                                    ChatMessageContent::Multipart(vec![ChatMessagePart::Image {
474                                        image_url: ImageUrl {
475                                            url: image.to_base64_url(),
476                                        },
477                                    }])
478                                } else {
479                                    debug_panic!(
480                                        "This should be caught at {} level",
481                                        tool_result.tool_name
482                                    );
483                                    "[Tool responded with an image, but this model does not support vision]".to_string().into()
484                                }
485                            }
486                        };
487
488                        messages.push(ChatMessage::Tool {
489                            tool_call_id: tool_result.tool_use_id.to_string(),
490                            content,
491                        });
492                    }
493                }
494
495                let mut content_parts = Vec::new();
496                for content in &message.content {
497                    match content {
498                        MessageContent::Text(text) | MessageContent::Thinking { text, .. }
499                            if !text.is_empty() =>
500                        {
501                            if let Some(ChatMessagePart::Text { text: text_content }) =
502                                content_parts.last_mut()
503                            {
504                                text_content.push_str(text);
505                            } else {
506                                content_parts.push(ChatMessagePart::Text {
507                                    text: text.to_string(),
508                                });
509                            }
510                        }
511                        MessageContent::Image(image) if model.supports_vision() => {
512                            content_parts.push(ChatMessagePart::Image {
513                                image_url: ImageUrl {
514                                    url: image.to_base64_url(),
515                                },
516                            });
517                        }
518                        _ => {}
519                    }
520                }
521
522                if !content_parts.is_empty() {
523                    messages.push(ChatMessage::User {
524                        content: content_parts.into(),
525                    });
526                }
527            }
528            Role::Assistant => {
529                let mut tool_calls = Vec::new();
530                for content in &message.content {
531                    if let MessageContent::ToolUse(tool_use) = content {
532                        tool_called = true;
533                        tool_calls.push(ToolCall {
534                            id: tool_use.id.to_string(),
535                            content: copilot::copilot_chat::ToolCallContent::Function {
536                                function: copilot::copilot_chat::FunctionContent {
537                                    name: tool_use.name.to_string(),
538                                    arguments: serde_json::to_string(&tool_use.input)?,
539                                },
540                            },
541                        });
542                    }
543                }
544
545                let text_content = {
546                    let mut buffer = String::new();
547                    for string in message.content.iter().filter_map(|content| match content {
548                        MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
549                            Some(text.as_str())
550                        }
551                        MessageContent::ToolUse(_)
552                        | MessageContent::RedactedThinking(_)
553                        | MessageContent::ToolResult(_)
554                        | MessageContent::Image(_) => None,
555                    }) {
556                        buffer.push_str(string);
557                    }
558
559                    buffer
560                };
561
562                messages.push(ChatMessage::Assistant {
563                    content: if text_content.is_empty() {
564                        ChatMessageContent::empty()
565                    } else {
566                        text_content.into()
567                    },
568                    tool_calls,
569                });
570            }
571            Role::System => messages.push(ChatMessage::System {
572                content: message.string_contents(),
573            }),
574        }
575    }
576
577    let mut tools = request
578        .tools
579        .iter()
580        .map(|tool| Tool::Function {
581            function: copilot::copilot_chat::Function {
582                name: tool.name.clone(),
583                description: tool.description.clone(),
584                parameters: tool.input_schema.clone(),
585            },
586        })
587        .collect::<Vec<_>>();
588
589    // The API will return a Bad Request (with no error message) when tools
590    // were used previously in the conversation but no tools are provided as
591    // part of this request. Inserting a dummy tool seems to circumvent this
592    // error.
593    if tool_called && tools.is_empty() {
594        tools.push(Tool::Function {
595            function: copilot::copilot_chat::Function {
596                name: "noop".to_string(),
597                description: "No operation".to_string(),
598                parameters: serde_json::json!({
599                    "type": "object"
600                }),
601            },
602        });
603    }
604
605    Ok(CopilotChatRequest {
606        intent: true,
607        n: 1,
608        stream: model.uses_streaming(),
609        temperature: 0.1,
610        model: model.id().to_string(),
611        messages,
612        tools,
613        tool_choice: request.tool_choice.map(|choice| match choice {
614            LanguageModelToolChoice::Auto => copilot::copilot_chat::ToolChoice::Auto,
615            LanguageModelToolChoice::Any => copilot::copilot_chat::ToolChoice::Any,
616            LanguageModelToolChoice::None => copilot::copilot_chat::ToolChoice::None,
617        }),
618    })
619}
620
621struct ConfigurationView {
622    copilot_status: Option<copilot::Status>,
623    api_url_editor: Entity<Editor>,
624    models_url_editor: Entity<Editor>,
625    auth_url_editor: Entity<Editor>,
626    state: Entity<State>,
627    _subscription: Option<Subscription>,
628}
629
630impl ConfigurationView {
631    pub fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
632        let copilot = Copilot::global(cx);
633        let settings = AllLanguageModelSettings::get_global(cx)
634            .copilot_chat
635            .clone();
636        let api_url_editor = cx.new(|cx| Editor::single_line(window, cx));
637        api_url_editor.update(cx, |this, cx| {
638            this.set_text(settings.api_url.clone(), window, cx);
639            this.set_placeholder_text("GitHub Copilot API URL", cx);
640        });
641        let models_url_editor = cx.new(|cx| Editor::single_line(window, cx));
642        models_url_editor.update(cx, |this, cx| {
643            this.set_text(settings.models_url.clone(), window, cx);
644            this.set_placeholder_text("GitHub Copilot Models URL", cx);
645        });
646        let auth_url_editor = cx.new(|cx| Editor::single_line(window, cx));
647        auth_url_editor.update(cx, |this, cx| {
648            this.set_text(settings.auth_url.clone(), window, cx);
649            this.set_placeholder_text("GitHub Copilot Auth URL", cx);
650        });
651        Self {
652            api_url_editor,
653            models_url_editor,
654            auth_url_editor,
655            copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
656            state,
657            _subscription: copilot.as_ref().map(|copilot| {
658                cx.observe(copilot, |this, model, cx| {
659                    this.copilot_status = Some(model.read(cx).status());
660                    cx.notify();
661                })
662            }),
663        }
664    }
665    fn make_input_styles(&self, cx: &App) -> Div {
666        let bg_color = cx.theme().colors().editor_background;
667        let border_color = cx.theme().colors().border;
668
669        h_flex()
670            .w_full()
671            .px_2()
672            .py_1()
673            .bg(bg_color)
674            .border_1()
675            .border_color(border_color)
676            .rounded_sm()
677    }
678
679    fn make_text_style(&self, cx: &Context<Self>) -> TextStyle {
680        let settings = ThemeSettings::get_global(cx);
681        TextStyle {
682            color: cx.theme().colors().text,
683            font_family: settings.ui_font.family.clone(),
684            font_features: settings.ui_font.features.clone(),
685            font_fallbacks: settings.ui_font.fallbacks.clone(),
686            font_size: rems(0.875).into(),
687            font_weight: settings.ui_font.weight,
688            font_style: FontStyle::Normal,
689            line_height: relative(1.3),
690            background_color: None,
691            underline: None,
692            strikethrough: None,
693            white_space: WhiteSpace::Normal,
694            text_overflow: None,
695            text_align: Default::default(),
696            line_clamp: None,
697        }
698    }
699
700    fn render_api_url_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
701        let text_style = self.make_text_style(cx);
702
703        EditorElement::new(
704            &self.api_url_editor,
705            EditorStyle {
706                background: cx.theme().colors().editor_background,
707                local_player: cx.theme().players().local(),
708                text: text_style,
709                ..Default::default()
710            },
711        )
712    }
713
714    fn render_auth_url_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
715        let text_style = self.make_text_style(cx);
716
717        EditorElement::new(
718            &self.auth_url_editor,
719            EditorStyle {
720                background: cx.theme().colors().editor_background,
721                local_player: cx.theme().players().local(),
722                text: text_style,
723                ..Default::default()
724            },
725        )
726    }
727    fn render_models_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
728        let text_style = self.make_text_style(cx);
729
730        EditorElement::new(
731            &self.models_url_editor,
732            EditorStyle {
733                background: cx.theme().colors().editor_background,
734                local_player: cx.theme().players().local(),
735                text: text_style,
736                ..Default::default()
737            },
738        )
739    }
740
741    fn update_copilot_settings(&self, cx: &mut Context<'_, Self>) {
742        let settings = CopilotChatSettings {
743            api_url: self.api_url_editor.read(cx).text(cx).into(),
744            models_url: self.models_url_editor.read(cx).text(cx).into(),
745            auth_url: self.auth_url_editor.read(cx).text(cx).into(),
746        };
747        update_settings_file::<AllLanguageModelSettings>(<dyn Fs>::global(cx), cx, {
748            let settings = settings.clone();
749            move |content, _| {
750                content.copilot_chat = Some(CopilotChatSettingsContent {
751                    api_url: Some(settings.api_url.as_ref().into()),
752                    models_url: Some(settings.models_url.as_ref().into()),
753                    auth_url: Some(settings.auth_url.as_ref().into()),
754                });
755            }
756        });
757        if let Some(chat) = CopilotChat::global(cx) {
758            chat.update(cx, |this, cx| {
759                this.set_settings(settings, cx);
760            });
761        }
762    }
763}
764
765impl Render for ConfigurationView {
766    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
767        if self.state.read(cx).is_authenticated(cx) {
768            h_flex()
769                .mt_1()
770                .p_1()
771                .justify_between()
772                .rounded_md()
773                .border_1()
774                .border_color(cx.theme().colors().border)
775                .bg(cx.theme().colors().background)
776                .child(
777                    h_flex()
778                        .gap_1()
779                        .child(Icon::new(IconName::Check).color(Color::Success))
780                        .child(Label::new("Authorized")),
781                )
782                .child(
783                    Button::new("sign_out", "Sign Out")
784                        .label_size(LabelSize::Small)
785                        .on_click(|_, window, cx| {
786                            window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
787                        }),
788                )
789        } else {
790            let loading_icon = Icon::new(IconName::ArrowCircle).with_animation(
791                "arrow-circle",
792                Animation::new(Duration::from_secs(4)).repeat(),
793                |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
794            );
795
796            const ERROR_LABEL: &str = "Copilot Chat requires an active GitHub Copilot subscription. Please ensure Copilot is configured and try again, or use a different Assistant provider.";
797
798            match &self.copilot_status {
799                Some(status) => match status {
800                    Status::Starting { task: _ } => h_flex()
801                        .gap_2()
802                        .child(loading_icon)
803                        .child(Label::new("Starting Copilot…")),
804                    Status::SigningIn { prompt: _ }
805                    | Status::SignedOut {
806                        awaiting_signing_in: true,
807                    } => h_flex()
808                        .gap_2()
809                        .child(loading_icon)
810                        .child(Label::new("Signing into Copilot…")),
811                    Status::Error(_) => {
812                        const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
813                        v_flex()
814                            .gap_6()
815                            .child(Label::new(LABEL))
816                            .child(svg().size_8().path(IconName::CopilotError.path()))
817                    }
818                    _ => {
819                        const LABEL: &str = "To use Zed's assistant with GitHub Copilot, you need to be logged in to GitHub. Note that your GitHub account must have an active Copilot Chat subscription.";
820                        v_flex()
821                            .gap_2()
822                            .child(Label::new(LABEL))
823                            .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
824                                this.update_copilot_settings(cx);
825                                copilot::initiate_sign_in(window, cx);
826                            }))
827                            .child(
828                                v_flex()
829                                    .gap_0p5()
830                                    .child(Label::new("API URL").size(LabelSize::Small))
831                                    .child(
832                                        self.make_input_styles(cx)
833                                            .child(self.render_api_url_editor(cx)),
834                                    ),
835                            )
836                            .child(
837                                v_flex()
838                                    .gap_0p5()
839                                    .child(Label::new("Auth URL").size(LabelSize::Small))
840                                    .child(
841                                        self.make_input_styles(cx)
842                                            .child(self.render_auth_url_editor(cx)),
843                                    ),
844                            )
845                            .child(
846                                v_flex()
847                                    .gap_0p5()
848                                    .child(Label::new("Models list URL").size(LabelSize::Small))
849                                    .child(
850                                        self.make_input_styles(cx)
851                                            .child(self.render_models_editor(cx)),
852                                    ),
853                            )
854                            .child(
855                                Button::new("sign_in", "Sign in to use GitHub Copilot")
856                                    .icon_color(Color::Muted)
857                                    .icon(IconName::Github)
858                                    .icon_position(IconPosition::Start)
859                                    .icon_size(IconSize::Medium)
860                                    .full_width()
861                                    .on_click(cx.listener(|this, _, window, cx| {
862                                        this.update_copilot_settings(cx);
863                                        copilot::initiate_sign_in(window, cx)
864                                    })),
865                            )
866                    }
867                },
868                None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
869            }
870        }
871    }
872}