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 LanguageModelCompletionError,
269 >,
270 > {
271 if let Some(message) = request.messages.last() {
272 if message.contents_empty() {
273 const EMPTY_PROMPT_MSG: &str =
274 "Empty prompts aren't allowed. Please provide a non-empty prompt.";
275 return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG).into()))
276 .boxed();
277 }
278
279 // Copilot Chat has a restriction that the final message must be from the user.
280 // While their API does return an error message for this, we can catch it earlier
281 // and provide a more helpful error message.
282 if !matches!(message.role, Role::User) {
283 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.";
284 return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG).into())).boxed();
285 }
286 }
287
288 let copilot_request = match into_copilot_chat(&self.model, request) {
289 Ok(request) => request,
290 Err(err) => return futures::future::ready(Err(err.into())).boxed(),
291 };
292 let is_streaming = copilot_request.stream;
293
294 let request_limiter = self.request_limiter.clone();
295 let future = cx.spawn(async move |cx| {
296 let request = CopilotChat::stream_completion(copilot_request, cx.clone());
297 request_limiter
298 .stream(async move {
299 let response = request.await?;
300 Ok(map_to_language_model_completion_events(
301 response,
302 is_streaming,
303 ))
304 })
305 .await
306 });
307 async move { Ok(future.await?.boxed()) }.boxed()
308 }
309}
310
311pub fn map_to_language_model_completion_events(
312 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
313 is_streaming: bool,
314) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
315 #[derive(Default)]
316 struct RawToolCall {
317 id: String,
318 name: String,
319 arguments: String,
320 }
321
322 struct State {
323 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
324 tool_calls_by_index: HashMap<usize, RawToolCall>,
325 }
326
327 futures::stream::unfold(
328 State {
329 events,
330 tool_calls_by_index: HashMap::default(),
331 },
332 move |mut state| async move {
333 if let Some(event) = state.events.next().await {
334 match event {
335 Ok(event) => {
336 let Some(choice) = event.choices.first() else {
337 return Some((
338 vec![Err(anyhow!("Response contained no choices").into())],
339 state,
340 ));
341 };
342
343 let delta = if is_streaming {
344 choice.delta.as_ref()
345 } else {
346 choice.message.as_ref()
347 };
348
349 let Some(delta) = delta else {
350 return Some((
351 vec![Err(anyhow!("Response contained no delta").into())],
352 state,
353 ));
354 };
355
356 let mut events = Vec::new();
357 if let Some(content) = delta.content.clone() {
358 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
359 }
360
361 for tool_call in &delta.tool_calls {
362 let entry = state
363 .tool_calls_by_index
364 .entry(tool_call.index)
365 .or_default();
366
367 if let Some(tool_id) = tool_call.id.clone() {
368 entry.id = tool_id;
369 }
370
371 if let Some(function) = tool_call.function.as_ref() {
372 if let Some(name) = function.name.clone() {
373 entry.name = name;
374 }
375
376 if let Some(arguments) = function.arguments.clone() {
377 entry.arguments.push_str(&arguments);
378 }
379 }
380 }
381
382 match choice.finish_reason.as_deref() {
383 Some("stop") => {
384 events.push(Ok(LanguageModelCompletionEvent::Stop(
385 StopReason::EndTurn,
386 )));
387 }
388 Some("tool_calls") => {
389 events.extend(state.tool_calls_by_index.drain().map(
390 |(_, tool_call)| {
391 // The model can output an empty string
392 // to indicate the absence of arguments.
393 // When that happens, create an empty
394 // object instead.
395 let arguments = if tool_call.arguments.is_empty() {
396 Ok(serde_json::Value::Object(Default::default()))
397 } else {
398 serde_json::Value::from_str(&tool_call.arguments)
399 };
400 match arguments {
401 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
402 LanguageModelToolUse {
403 id: tool_call.id.clone().into(),
404 name: tool_call.name.as_str().into(),
405 is_input_complete: true,
406 input,
407 raw_input: tool_call.arguments.clone(),
408 },
409 )),
410 Err(error) => {
411 Err(LanguageModelCompletionError::BadInputJson {
412 id: tool_call.id.into(),
413 tool_name: tool_call.name.as_str().into(),
414 raw_input: tool_call.arguments.into(),
415 json_parse_error: error.to_string(),
416 })
417 }
418 }
419 },
420 ));
421
422 events.push(Ok(LanguageModelCompletionEvent::Stop(
423 StopReason::ToolUse,
424 )));
425 }
426 Some(stop_reason) => {
427 log::error!("Unexpected Copilot Chat stop_reason: {stop_reason:?}");
428 events.push(Ok(LanguageModelCompletionEvent::Stop(
429 StopReason::EndTurn,
430 )));
431 }
432 None => {}
433 }
434
435 return Some((events, state));
436 }
437 Err(err) => return Some((vec![Err(anyhow!(err).into())], state)),
438 }
439 }
440
441 None
442 },
443 )
444 .flat_map(futures::stream::iter)
445}
446
447fn into_copilot_chat(
448 model: &copilot::copilot_chat::Model,
449 request: LanguageModelRequest,
450) -> Result<CopilotChatRequest> {
451 let mut request_messages: Vec<LanguageModelRequestMessage> = Vec::new();
452 for message in request.messages {
453 if let Some(last_message) = request_messages.last_mut() {
454 if last_message.role == message.role {
455 last_message.content.extend(message.content);
456 } else {
457 request_messages.push(message);
458 }
459 } else {
460 request_messages.push(message);
461 }
462 }
463
464 let mut tool_called = false;
465 let mut messages: Vec<ChatMessage> = Vec::new();
466 for message in request_messages {
467 match message.role {
468 Role::User => {
469 for content in &message.content {
470 if let MessageContent::ToolResult(tool_result) = content {
471 let content = match &tool_result.content {
472 LanguageModelToolResultContent::Text(text) => text.to_string().into(),
473 LanguageModelToolResultContent::Image(image) => {
474 if model.supports_vision() {
475 ChatMessageContent::Multipart(vec![ChatMessagePart::Image {
476 image_url: ImageUrl {
477 url: image.to_base64_url(),
478 },
479 }])
480 } else {
481 debug_panic!(
482 "This should be caught at {} level",
483 tool_result.tool_name
484 );
485 "[Tool responded with an image, but this model does not support vision]".to_string().into()
486 }
487 }
488 };
489
490 messages.push(ChatMessage::Tool {
491 tool_call_id: tool_result.tool_use_id.to_string(),
492 content,
493 });
494 }
495 }
496
497 let mut content_parts = Vec::new();
498 for content in &message.content {
499 match content {
500 MessageContent::Text(text) | MessageContent::Thinking { text, .. }
501 if !text.is_empty() =>
502 {
503 if let Some(ChatMessagePart::Text { text: text_content }) =
504 content_parts.last_mut()
505 {
506 text_content.push_str(text);
507 } else {
508 content_parts.push(ChatMessagePart::Text {
509 text: text.to_string(),
510 });
511 }
512 }
513 MessageContent::Image(image) if model.supports_vision() => {
514 content_parts.push(ChatMessagePart::Image {
515 image_url: ImageUrl {
516 url: image.to_base64_url(),
517 },
518 });
519 }
520 _ => {}
521 }
522 }
523
524 if !content_parts.is_empty() {
525 messages.push(ChatMessage::User {
526 content: content_parts.into(),
527 });
528 }
529 }
530 Role::Assistant => {
531 let mut tool_calls = Vec::new();
532 for content in &message.content {
533 if let MessageContent::ToolUse(tool_use) = content {
534 tool_called = true;
535 tool_calls.push(ToolCall {
536 id: tool_use.id.to_string(),
537 content: copilot::copilot_chat::ToolCallContent::Function {
538 function: copilot::copilot_chat::FunctionContent {
539 name: tool_use.name.to_string(),
540 arguments: serde_json::to_string(&tool_use.input)?,
541 },
542 },
543 });
544 }
545 }
546
547 let text_content = {
548 let mut buffer = String::new();
549 for string in message.content.iter().filter_map(|content| match content {
550 MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
551 Some(text.as_str())
552 }
553 MessageContent::ToolUse(_)
554 | MessageContent::RedactedThinking(_)
555 | MessageContent::ToolResult(_)
556 | MessageContent::Image(_) => None,
557 }) {
558 buffer.push_str(string);
559 }
560
561 buffer
562 };
563
564 messages.push(ChatMessage::Assistant {
565 content: if text_content.is_empty() {
566 ChatMessageContent::empty()
567 } else {
568 text_content.into()
569 },
570 tool_calls,
571 });
572 }
573 Role::System => messages.push(ChatMessage::System {
574 content: message.string_contents(),
575 }),
576 }
577 }
578
579 let mut tools = request
580 .tools
581 .iter()
582 .map(|tool| Tool::Function {
583 function: copilot::copilot_chat::Function {
584 name: tool.name.clone(),
585 description: tool.description.clone(),
586 parameters: tool.input_schema.clone(),
587 },
588 })
589 .collect::<Vec<_>>();
590
591 // The API will return a Bad Request (with no error message) when tools
592 // were used previously in the conversation but no tools are provided as
593 // part of this request. Inserting a dummy tool seems to circumvent this
594 // error.
595 if tool_called && tools.is_empty() {
596 tools.push(Tool::Function {
597 function: copilot::copilot_chat::Function {
598 name: "noop".to_string(),
599 description: "No operation".to_string(),
600 parameters: serde_json::json!({
601 "type": "object"
602 }),
603 },
604 });
605 }
606
607 Ok(CopilotChatRequest {
608 intent: true,
609 n: 1,
610 stream: model.uses_streaming(),
611 temperature: 0.1,
612 model: model.id().to_string(),
613 messages,
614 tools,
615 tool_choice: request.tool_choice.map(|choice| match choice {
616 LanguageModelToolChoice::Auto => copilot::copilot_chat::ToolChoice::Auto,
617 LanguageModelToolChoice::Any => copilot::copilot_chat::ToolChoice::Any,
618 LanguageModelToolChoice::None => copilot::copilot_chat::ToolChoice::None,
619 }),
620 })
621}
622
623struct ConfigurationView {
624 copilot_status: Option<copilot::Status>,
625 api_url_editor: Entity<Editor>,
626 models_url_editor: Entity<Editor>,
627 auth_url_editor: Entity<Editor>,
628 state: Entity<State>,
629 _subscription: Option<Subscription>,
630}
631
632impl ConfigurationView {
633 pub fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
634 let copilot = Copilot::global(cx);
635 let settings = AllLanguageModelSettings::get_global(cx)
636 .copilot_chat
637 .clone();
638 let api_url_editor = cx.new(|cx| Editor::single_line(window, cx));
639 api_url_editor.update(cx, |this, cx| {
640 this.set_text(settings.api_url.clone(), window, cx);
641 this.set_placeholder_text("GitHub Copilot API URL", cx);
642 });
643 let models_url_editor = cx.new(|cx| Editor::single_line(window, cx));
644 models_url_editor.update(cx, |this, cx| {
645 this.set_text(settings.models_url.clone(), window, cx);
646 this.set_placeholder_text("GitHub Copilot Models URL", cx);
647 });
648 let auth_url_editor = cx.new(|cx| Editor::single_line(window, cx));
649 auth_url_editor.update(cx, |this, cx| {
650 this.set_text(settings.auth_url.clone(), window, cx);
651 this.set_placeholder_text("GitHub Copilot Auth URL", cx);
652 });
653 Self {
654 api_url_editor,
655 models_url_editor,
656 auth_url_editor,
657 copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
658 state,
659 _subscription: copilot.as_ref().map(|copilot| {
660 cx.observe(copilot, |this, model, cx| {
661 this.copilot_status = Some(model.read(cx).status());
662 cx.notify();
663 })
664 }),
665 }
666 }
667 fn make_input_styles(&self, cx: &App) -> Div {
668 let bg_color = cx.theme().colors().editor_background;
669 let border_color = cx.theme().colors().border;
670
671 h_flex()
672 .w_full()
673 .px_2()
674 .py_1()
675 .bg(bg_color)
676 .border_1()
677 .border_color(border_color)
678 .rounded_sm()
679 }
680
681 fn make_text_style(&self, cx: &Context<Self>) -> TextStyle {
682 let settings = ThemeSettings::get_global(cx);
683 TextStyle {
684 color: cx.theme().colors().text,
685 font_family: settings.ui_font.family.clone(),
686 font_features: settings.ui_font.features.clone(),
687 font_fallbacks: settings.ui_font.fallbacks.clone(),
688 font_size: rems(0.875).into(),
689 font_weight: settings.ui_font.weight,
690 font_style: FontStyle::Normal,
691 line_height: relative(1.3),
692 background_color: None,
693 underline: None,
694 strikethrough: None,
695 white_space: WhiteSpace::Normal,
696 text_overflow: None,
697 text_align: Default::default(),
698 line_clamp: None,
699 }
700 }
701
702 fn render_api_url_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
703 let text_style = self.make_text_style(cx);
704
705 EditorElement::new(
706 &self.api_url_editor,
707 EditorStyle {
708 background: cx.theme().colors().editor_background,
709 local_player: cx.theme().players().local(),
710 text: text_style,
711 ..Default::default()
712 },
713 )
714 }
715
716 fn render_auth_url_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
717 let text_style = self.make_text_style(cx);
718
719 EditorElement::new(
720 &self.auth_url_editor,
721 EditorStyle {
722 background: cx.theme().colors().editor_background,
723 local_player: cx.theme().players().local(),
724 text: text_style,
725 ..Default::default()
726 },
727 )
728 }
729 fn render_models_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
730 let text_style = self.make_text_style(cx);
731
732 EditorElement::new(
733 &self.models_url_editor,
734 EditorStyle {
735 background: cx.theme().colors().editor_background,
736 local_player: cx.theme().players().local(),
737 text: text_style,
738 ..Default::default()
739 },
740 )
741 }
742
743 fn update_copilot_settings(&self, cx: &mut Context<'_, Self>) {
744 let settings = CopilotChatSettings {
745 api_url: self.api_url_editor.read(cx).text(cx).into(),
746 models_url: self.models_url_editor.read(cx).text(cx).into(),
747 auth_url: self.auth_url_editor.read(cx).text(cx).into(),
748 };
749 update_settings_file::<AllLanguageModelSettings>(<dyn Fs>::global(cx), cx, {
750 let settings = settings.clone();
751 move |content, _| {
752 content.copilot_chat = Some(CopilotChatSettingsContent {
753 api_url: Some(settings.api_url.as_ref().into()),
754 models_url: Some(settings.models_url.as_ref().into()),
755 auth_url: Some(settings.auth_url.as_ref().into()),
756 });
757 }
758 });
759 if let Some(chat) = CopilotChat::global(cx) {
760 chat.update(cx, |this, cx| {
761 this.set_settings(settings, cx);
762 });
763 }
764 }
765}
766
767impl Render for ConfigurationView {
768 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
769 if self.state.read(cx).is_authenticated(cx) {
770 h_flex()
771 .mt_1()
772 .p_1()
773 .justify_between()
774 .rounded_md()
775 .border_1()
776 .border_color(cx.theme().colors().border)
777 .bg(cx.theme().colors().background)
778 .child(
779 h_flex()
780 .gap_1()
781 .child(Icon::new(IconName::Check).color(Color::Success))
782 .child(Label::new("Authorized")),
783 )
784 .child(
785 Button::new("sign_out", "Sign Out")
786 .label_size(LabelSize::Small)
787 .on_click(|_, window, cx| {
788 window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
789 }),
790 )
791 } else {
792 let loading_icon = Icon::new(IconName::ArrowCircle).with_animation(
793 "arrow-circle",
794 Animation::new(Duration::from_secs(4)).repeat(),
795 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
796 );
797
798 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.";
799
800 match &self.copilot_status {
801 Some(status) => match status {
802 Status::Starting { task: _ } => h_flex()
803 .gap_2()
804 .child(loading_icon)
805 .child(Label::new("Starting Copilot…")),
806 Status::SigningIn { prompt: _ }
807 | Status::SignedOut {
808 awaiting_signing_in: true,
809 } => h_flex()
810 .gap_2()
811 .child(loading_icon)
812 .child(Label::new("Signing into Copilot…")),
813 Status::Error(_) => {
814 const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
815 v_flex()
816 .gap_6()
817 .child(Label::new(LABEL))
818 .child(svg().size_8().path(IconName::CopilotError.path()))
819 }
820 _ => {
821 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.";
822 v_flex()
823 .gap_2()
824 .child(Label::new(LABEL))
825 .on_action(cx.listener(|this, _: &menu::Confirm, window, cx| {
826 this.update_copilot_settings(cx);
827 copilot::initiate_sign_in(window, cx);
828 }))
829 .child(
830 v_flex()
831 .gap_0p5()
832 .child(Label::new("API URL").size(LabelSize::Small))
833 .child(
834 self.make_input_styles(cx)
835 .child(self.render_api_url_editor(cx)),
836 ),
837 )
838 .child(
839 v_flex()
840 .gap_0p5()
841 .child(Label::new("Auth URL").size(LabelSize::Small))
842 .child(
843 self.make_input_styles(cx)
844 .child(self.render_auth_url_editor(cx)),
845 ),
846 )
847 .child(
848 v_flex()
849 .gap_0p5()
850 .child(Label::new("Models list URL").size(LabelSize::Small))
851 .child(
852 self.make_input_styles(cx)
853 .child(self.render_models_editor(cx)),
854 ),
855 )
856 .child(
857 Button::new("sign_in", "Sign in to use GitHub Copilot")
858 .icon_color(Color::Muted)
859 .icon(IconName::Github)
860 .icon_position(IconPosition::Start)
861 .icon_size(IconSize::Medium)
862 .full_width()
863 .on_click(cx.listener(|this, _, window, cx| {
864 this.update_copilot_settings(cx);
865 copilot::initiate_sign_in(window, cx)
866 })),
867 )
868 .child(
869 Label::new(
870 format!("You can also assign the {} environment variable and restart Zed.", copilot::copilot_chat::COPILOT_OAUTH_ENV_VAR),
871 )
872 .size(LabelSize::Small)
873 .color(Color::Muted),
874 )
875 }
876 },
877 None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
878 }
879 }
880 }
881}