cloud.rs

  1use super::open_ai::count_open_ai_tokens;
  2use crate::provider::anthropic::map_to_language_model_completion_events;
  3use crate::{
  4    settings::AllLanguageModelSettings, CloudModel, LanguageModel, LanguageModelCacheConfiguration,
  5    LanguageModelId, LanguageModelName, LanguageModelProviderId, LanguageModelProviderName,
  6    LanguageModelProviderState, LanguageModelRequest, RateLimiter,
  7};
  8use anthropic::AnthropicError;
  9use anyhow::{anyhow, Result};
 10use client::{Client, PerformCompletionParams, UserStore, EXPIRED_LLM_TOKEN_HEADER_NAME};
 11use collections::BTreeMap;
 12use feature_flags::{FeatureFlagAppExt, LlmClosedBeta, ZedPro};
 13use futures::{
 14    future::BoxFuture, stream::BoxStream, AsyncBufReadExt, FutureExt, Stream, StreamExt,
 15    TryStreamExt as _,
 16};
 17use gpui::{
 18    AnyElement, AnyView, AppContext, AsyncAppContext, FontWeight, Model, ModelContext,
 19    Subscription, Task,
 20};
 21use http_client::{AsyncBody, HttpClient, HttpRequestExt, Method, Response};
 22use schemars::JsonSchema;
 23use serde::{de::DeserializeOwned, Deserialize, Serialize};
 24use serde_json::value::RawValue;
 25use settings::{Settings, SettingsStore};
 26use smol::{
 27    io::{AsyncReadExt, BufReader},
 28    lock::{RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard},
 29};
 30use std::time::Duration;
 31use std::{
 32    future,
 33    sync::{Arc, LazyLock},
 34};
 35use strum::IntoEnumIterator;
 36use ui::{prelude::*, TintColor};
 37
 38use crate::{LanguageModelAvailability, LanguageModelCompletionEvent, LanguageModelProvider};
 39
 40use super::anthropic::count_anthropic_tokens;
 41
 42pub const PROVIDER_ID: &str = "zed.dev";
 43pub const PROVIDER_NAME: &str = "Zed";
 44
 45const ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: Option<&str> =
 46    option_env!("ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON");
 47
 48fn zed_cloud_provider_additional_models() -> &'static [AvailableModel] {
 49    static ADDITIONAL_MODELS: LazyLock<Vec<AvailableModel>> = LazyLock::new(|| {
 50        ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON
 51            .map(|json| serde_json::from_str(json).unwrap())
 52            .unwrap_or_default()
 53    });
 54    ADDITIONAL_MODELS.as_slice()
 55}
 56
 57#[derive(Default, Clone, Debug, PartialEq)]
 58pub struct ZedDotDevSettings {
 59    pub available_models: Vec<AvailableModel>,
 60    pub low_speed_timeout: Option<Duration>,
 61}
 62
 63#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 64#[serde(rename_all = "lowercase")]
 65pub enum AvailableProvider {
 66    Anthropic,
 67    OpenAi,
 68    Google,
 69}
 70
 71#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 72pub struct AvailableModel {
 73    /// The provider of the language model.
 74    pub provider: AvailableProvider,
 75    /// The model's name in the provider's API. e.g. claude-3-5-sonnet-20240620
 76    pub name: String,
 77    /// The name displayed in the UI, such as in the assistant panel model dropdown menu.
 78    pub display_name: Option<String>,
 79    /// The size of the context window, indicating the maximum number of tokens the model can process.
 80    pub max_tokens: usize,
 81    /// The maximum number of output tokens allowed by the model.
 82    pub max_output_tokens: Option<u32>,
 83    /// The maximum number of completion tokens allowed by the model (o1-* only)
 84    pub max_completion_tokens: Option<u32>,
 85    /// Override this model with a different Anthropic model for tool calls.
 86    pub tool_override: Option<String>,
 87    /// Indicates whether this custom model supports caching.
 88    pub cache_configuration: Option<LanguageModelCacheConfiguration>,
 89    /// The default temperature to use for this model.
 90    pub default_temperature: Option<f32>,
 91}
 92
 93pub struct CloudLanguageModelProvider {
 94    client: Arc<Client>,
 95    llm_api_token: LlmApiToken,
 96    state: gpui::Model<State>,
 97    _maintain_client_status: Task<()>,
 98}
 99
100pub struct State {
101    client: Arc<Client>,
102    user_store: Model<UserStore>,
103    status: client::Status,
104    accept_terms: Option<Task<Result<()>>>,
105    _subscription: Subscription,
106}
107
108impl State {
109    fn is_signed_out(&self) -> bool {
110        self.status.is_signed_out()
111    }
112
113    fn authenticate(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
114        let client = self.client.clone();
115        cx.spawn(move |this, mut cx| async move {
116            client.authenticate_and_connect(true, &cx).await?;
117            this.update(&mut cx, |_, cx| cx.notify())
118        })
119    }
120
121    fn has_accepted_terms_of_service(&self, cx: &AppContext) -> bool {
122        self.user_store
123            .read(cx)
124            .current_user_has_accepted_terms()
125            .unwrap_or(false)
126    }
127
128    fn accept_terms_of_service(&mut self, cx: &mut ModelContext<Self>) {
129        let user_store = self.user_store.clone();
130        self.accept_terms = Some(cx.spawn(move |this, mut cx| async move {
131            let _ = user_store
132                .update(&mut cx, |store, cx| store.accept_terms_of_service(cx))?
133                .await;
134            this.update(&mut cx, |this, cx| {
135                this.accept_terms = None;
136                cx.notify()
137            })
138        }));
139    }
140}
141
142impl CloudLanguageModelProvider {
143    pub fn new(user_store: Model<UserStore>, client: Arc<Client>, cx: &mut AppContext) -> Self {
144        let mut status_rx = client.status();
145        let status = *status_rx.borrow();
146
147        let state = cx.new_model(|cx| State {
148            client: client.clone(),
149            user_store,
150            status,
151            accept_terms: None,
152            _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
153                cx.notify();
154            }),
155        });
156
157        let state_ref = state.downgrade();
158        let maintain_client_status = cx.spawn(|mut cx| async move {
159            while let Some(status) = status_rx.next().await {
160                if let Some(this) = state_ref.upgrade() {
161                    _ = this.update(&mut cx, |this, cx| {
162                        if this.status != status {
163                            this.status = status;
164                            cx.notify();
165                        }
166                    });
167                } else {
168                    break;
169                }
170            }
171        });
172
173        Self {
174            client,
175            state,
176            llm_api_token: LlmApiToken::default(),
177            _maintain_client_status: maintain_client_status,
178        }
179    }
180}
181
182impl LanguageModelProviderState for CloudLanguageModelProvider {
183    type ObservableEntity = State;
184
185    fn observable_entity(&self) -> Option<gpui::Model<Self::ObservableEntity>> {
186        Some(self.state.clone())
187    }
188}
189
190impl LanguageModelProvider for CloudLanguageModelProvider {
191    fn id(&self) -> LanguageModelProviderId {
192        LanguageModelProviderId(PROVIDER_ID.into())
193    }
194
195    fn name(&self) -> LanguageModelProviderName {
196        LanguageModelProviderName(PROVIDER_NAME.into())
197    }
198
199    fn icon(&self) -> IconName {
200        IconName::AiZed
201    }
202
203    fn provided_models(&self, cx: &AppContext) -> Vec<Arc<dyn LanguageModel>> {
204        let mut models = BTreeMap::default();
205
206        if cx.is_staff() {
207            for model in anthropic::Model::iter() {
208                if !matches!(model, anthropic::Model::Custom { .. }) {
209                    models.insert(model.id().to_string(), CloudModel::Anthropic(model));
210                }
211            }
212            for model in open_ai::Model::iter() {
213                if !matches!(model, open_ai::Model::Custom { .. }) {
214                    models.insert(model.id().to_string(), CloudModel::OpenAi(model));
215                }
216            }
217            for model in google_ai::Model::iter() {
218                if !matches!(model, google_ai::Model::Custom { .. }) {
219                    models.insert(model.id().to_string(), CloudModel::Google(model));
220                }
221            }
222        } else {
223            models.insert(
224                anthropic::Model::Claude3_5Sonnet.id().to_string(),
225                CloudModel::Anthropic(anthropic::Model::Claude3_5Sonnet),
226            );
227        }
228
229        let llm_closed_beta_models = if cx.has_flag::<LlmClosedBeta>() {
230            zed_cloud_provider_additional_models()
231        } else {
232            &[]
233        };
234
235        // Override with available models from settings
236        for model in AllLanguageModelSettings::get_global(cx)
237            .zed_dot_dev
238            .available_models
239            .iter()
240            .chain(llm_closed_beta_models)
241            .cloned()
242        {
243            let model = match model.provider {
244                AvailableProvider::Anthropic => CloudModel::Anthropic(anthropic::Model::Custom {
245                    name: model.name.clone(),
246                    display_name: model.display_name.clone(),
247                    max_tokens: model.max_tokens,
248                    tool_override: model.tool_override.clone(),
249                    cache_configuration: model.cache_configuration.as_ref().map(|config| {
250                        anthropic::AnthropicModelCacheConfiguration {
251                            max_cache_anchors: config.max_cache_anchors,
252                            should_speculate: config.should_speculate,
253                            min_total_token: config.min_total_token,
254                        }
255                    }),
256                    default_temperature: model.default_temperature,
257                    max_output_tokens: model.max_output_tokens,
258                }),
259                AvailableProvider::OpenAi => CloudModel::OpenAi(open_ai::Model::Custom {
260                    name: model.name.clone(),
261                    display_name: model.display_name.clone(),
262                    max_tokens: model.max_tokens,
263                    max_output_tokens: model.max_output_tokens,
264                    max_completion_tokens: model.max_completion_tokens,
265                }),
266                AvailableProvider::Google => CloudModel::Google(google_ai::Model::Custom {
267                    name: model.name.clone(),
268                    display_name: model.display_name.clone(),
269                    max_tokens: model.max_tokens,
270                }),
271            };
272            models.insert(model.id().to_string(), model.clone());
273        }
274
275        models
276            .into_values()
277            .map(|model| {
278                Arc::new(CloudLanguageModel {
279                    id: LanguageModelId::from(model.id().to_string()),
280                    model,
281                    llm_api_token: self.llm_api_token.clone(),
282                    client: self.client.clone(),
283                    request_limiter: RateLimiter::new(4),
284                }) as Arc<dyn LanguageModel>
285            })
286            .collect()
287    }
288
289    fn is_authenticated(&self, cx: &AppContext) -> bool {
290        !self.state.read(cx).is_signed_out()
291    }
292
293    fn authenticate(&self, _cx: &mut AppContext) -> Task<Result<()>> {
294        Task::ready(Ok(()))
295    }
296
297    fn configuration_view(&self, cx: &mut WindowContext) -> AnyView {
298        cx.new_view(|_cx| ConfigurationView {
299            state: self.state.clone(),
300        })
301        .into()
302    }
303
304    fn must_accept_terms(&self, cx: &AppContext) -> bool {
305        !self.state.read(cx).has_accepted_terms_of_service(cx)
306    }
307
308    fn render_accept_terms(&self, cx: &mut WindowContext) -> Option<AnyElement> {
309        let state = self.state.read(cx);
310
311        let terms = [(
312            "terms_of_service",
313            "Terms of Service",
314            "https://zed.dev/terms-of-service",
315        )]
316        .map(|(id, label, url)| {
317            Button::new(id, label)
318                .style(ButtonStyle::Subtle)
319                .icon(IconName::ExternalLink)
320                .icon_size(IconSize::XSmall)
321                .icon_color(Color::Muted)
322                .on_click(move |_, cx| cx.open_url(url))
323        });
324
325        if state.has_accepted_terms_of_service(cx) {
326            None
327        } else {
328            let disabled = state.accept_terms.is_some();
329            Some(
330                v_flex()
331                    .gap_2()
332                    .child(
333                        v_flex()
334                            .child(Label::new("Terms and Conditions").weight(FontWeight::MEDIUM))
335                            .child(
336                                Label::new(
337                                    "Please read and accept our terms and conditions to continue.",
338                                )
339                                .size(LabelSize::Small),
340                            ),
341                    )
342                    .child(v_flex().gap_1().children(terms))
343                    .child(
344                        h_flex().justify_end().child(
345                            Button::new("accept_terms", "I've read it and accept it")
346                                .disabled(disabled)
347                                .on_click({
348                                    let state = self.state.downgrade();
349                                    move |_, cx| {
350                                        state
351                                            .update(cx, |state, cx| {
352                                                state.accept_terms_of_service(cx)
353                                            })
354                                            .ok();
355                                    }
356                                }),
357                        ),
358                    )
359                    .into_any(),
360            )
361        }
362    }
363
364    fn reset_credentials(&self, _cx: &mut AppContext) -> Task<Result<()>> {
365        Task::ready(Ok(()))
366    }
367}
368
369pub struct CloudLanguageModel {
370    id: LanguageModelId,
371    model: CloudModel,
372    llm_api_token: LlmApiToken,
373    client: Arc<Client>,
374    request_limiter: RateLimiter,
375}
376
377#[derive(Clone, Default)]
378struct LlmApiToken(Arc<RwLock<Option<String>>>);
379
380impl CloudLanguageModel {
381    async fn perform_llm_completion(
382        client: Arc<Client>,
383        llm_api_token: LlmApiToken,
384        body: PerformCompletionParams,
385        low_speed_timeout: Option<Duration>,
386    ) -> Result<Response<AsyncBody>> {
387        let http_client = &client.http_client();
388
389        let mut token = llm_api_token.acquire(&client).await?;
390        let mut did_retry = false;
391
392        let response = loop {
393            let mut request_builder = http_client::Request::builder();
394            if let Some(low_speed_timeout) = low_speed_timeout {
395                request_builder = request_builder.read_timeout(low_speed_timeout);
396            };
397            let request = request_builder
398                .method(Method::POST)
399                .uri(http_client.build_zed_llm_url("/completion", &[])?.as_ref())
400                .header("Content-Type", "application/json")
401                .header("Authorization", format!("Bearer {token}"))
402                .body(serde_json::to_string(&body)?.into())?;
403            let mut response = http_client.send(request).await?;
404            if response.status().is_success() {
405                break response;
406            } else if !did_retry
407                && response
408                    .headers()
409                    .get(EXPIRED_LLM_TOKEN_HEADER_NAME)
410                    .is_some()
411            {
412                did_retry = true;
413                token = llm_api_token.refresh(&client).await?;
414            } else {
415                let mut body = String::new();
416                response.body_mut().read_to_string(&mut body).await?;
417                break Err(anyhow!(
418                    "cloud language model completion failed with status {}: {body}",
419                    response.status()
420                ))?;
421            }
422        };
423
424        Ok(response)
425    }
426}
427
428impl LanguageModel for CloudLanguageModel {
429    fn id(&self) -> LanguageModelId {
430        self.id.clone()
431    }
432
433    fn name(&self) -> LanguageModelName {
434        LanguageModelName::from(self.model.display_name().to_string())
435    }
436
437    fn icon(&self) -> Option<IconName> {
438        self.model.icon()
439    }
440
441    fn provider_id(&self) -> LanguageModelProviderId {
442        LanguageModelProviderId(PROVIDER_ID.into())
443    }
444
445    fn provider_name(&self) -> LanguageModelProviderName {
446        LanguageModelProviderName(PROVIDER_NAME.into())
447    }
448
449    fn telemetry_id(&self) -> String {
450        format!("zed.dev/{}", self.model.id())
451    }
452
453    fn availability(&self) -> LanguageModelAvailability {
454        self.model.availability()
455    }
456
457    fn max_token_count(&self) -> usize {
458        self.model.max_token_count()
459    }
460
461    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
462        match &self.model {
463            CloudModel::Anthropic(model) => {
464                model
465                    .cache_configuration()
466                    .map(|cache| LanguageModelCacheConfiguration {
467                        max_cache_anchors: cache.max_cache_anchors,
468                        should_speculate: cache.should_speculate,
469                        min_total_token: cache.min_total_token,
470                    })
471            }
472            CloudModel::OpenAi(_) | CloudModel::Google(_) => None,
473        }
474    }
475
476    fn count_tokens(
477        &self,
478        request: LanguageModelRequest,
479        cx: &AppContext,
480    ) -> BoxFuture<'static, Result<usize>> {
481        match self.model.clone() {
482            CloudModel::Anthropic(_) => count_anthropic_tokens(request, cx),
483            CloudModel::OpenAi(model) => count_open_ai_tokens(request, model, cx),
484            CloudModel::Google(model) => {
485                let client = self.client.clone();
486                let request = request.into_google(model.id().into());
487                let request = google_ai::CountTokensRequest {
488                    contents: request.contents,
489                };
490                async move {
491                    let request = serde_json::to_string(&request)?;
492                    let response = client
493                        .request(proto::CountLanguageModelTokens {
494                            provider: proto::LanguageModelProvider::Google as i32,
495                            request,
496                        })
497                        .await?;
498                    Ok(response.token_count as usize)
499                }
500                .boxed()
501            }
502        }
503    }
504
505    fn stream_completion(
506        &self,
507        request: LanguageModelRequest,
508        cx: &AsyncAppContext,
509    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
510        let openai_low_speed_timeout =
511            AllLanguageModelSettings::try_read_global(cx, |s| s.openai.low_speed_timeout.unwrap());
512
513        match &self.model {
514            CloudModel::Anthropic(model) => {
515                let request = request.into_anthropic(
516                    model.id().into(),
517                    model.default_temperature(),
518                    model.max_output_tokens(),
519                );
520                let client = self.client.clone();
521                let llm_api_token = self.llm_api_token.clone();
522                let future = self.request_limiter.stream(async move {
523                    let response = Self::perform_llm_completion(
524                        client.clone(),
525                        llm_api_token,
526                        PerformCompletionParams {
527                            provider: client::LanguageModelProvider::Anthropic,
528                            model: request.model.clone(),
529                            provider_request: RawValue::from_string(serde_json::to_string(
530                                &request,
531                            )?)?,
532                        },
533                        None,
534                    )
535                    .await?;
536                    Ok(map_to_language_model_completion_events(Box::pin(
537                        response_lines(response).map_err(AnthropicError::Other),
538                    )))
539                });
540                async move { Ok(future.await?.boxed()) }.boxed()
541            }
542            CloudModel::OpenAi(model) => {
543                let client = self.client.clone();
544                let request = request.into_open_ai(model.id().into(), model.max_output_tokens());
545                let llm_api_token = self.llm_api_token.clone();
546                let future = self.request_limiter.stream(async move {
547                    let response = Self::perform_llm_completion(
548                        client.clone(),
549                        llm_api_token,
550                        PerformCompletionParams {
551                            provider: client::LanguageModelProvider::OpenAi,
552                            model: request.model.clone(),
553                            provider_request: RawValue::from_string(serde_json::to_string(
554                                &request,
555                            )?)?,
556                        },
557                        openai_low_speed_timeout,
558                    )
559                    .await?;
560                    Ok(open_ai::extract_text_from_events(response_lines(response)))
561                });
562                async move {
563                    Ok(future
564                        .await?
565                        .map(|result| result.map(LanguageModelCompletionEvent::Text))
566                        .boxed())
567                }
568                .boxed()
569            }
570            CloudModel::Google(model) => {
571                let client = self.client.clone();
572                let request = request.into_google(model.id().into());
573                let llm_api_token = self.llm_api_token.clone();
574                let future = self.request_limiter.stream(async move {
575                    let response = Self::perform_llm_completion(
576                        client.clone(),
577                        llm_api_token,
578                        PerformCompletionParams {
579                            provider: client::LanguageModelProvider::Google,
580                            model: request.model.clone(),
581                            provider_request: RawValue::from_string(serde_json::to_string(
582                                &request,
583                            )?)?,
584                        },
585                        None,
586                    )
587                    .await?;
588                    Ok(google_ai::extract_text_from_events(response_lines(
589                        response,
590                    )))
591                });
592                async move {
593                    Ok(future
594                        .await?
595                        .map(|result| result.map(LanguageModelCompletionEvent::Text))
596                        .boxed())
597                }
598                .boxed()
599            }
600        }
601    }
602
603    fn use_any_tool(
604        &self,
605        request: LanguageModelRequest,
606        tool_name: String,
607        tool_description: String,
608        input_schema: serde_json::Value,
609        _cx: &AsyncAppContext,
610    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
611        let client = self.client.clone();
612        let llm_api_token = self.llm_api_token.clone();
613
614        match &self.model {
615            CloudModel::Anthropic(model) => {
616                let mut request = request.into_anthropic(
617                    model.tool_model_id().into(),
618                    model.default_temperature(),
619                    model.max_output_tokens(),
620                );
621                request.tool_choice = Some(anthropic::ToolChoice::Tool {
622                    name: tool_name.clone(),
623                });
624                request.tools = vec![anthropic::Tool {
625                    name: tool_name.clone(),
626                    description: tool_description,
627                    input_schema,
628                }];
629
630                self.request_limiter
631                    .run(async move {
632                        let response = Self::perform_llm_completion(
633                            client.clone(),
634                            llm_api_token,
635                            PerformCompletionParams {
636                                provider: client::LanguageModelProvider::Anthropic,
637                                model: request.model.clone(),
638                                provider_request: RawValue::from_string(serde_json::to_string(
639                                    &request,
640                                )?)?,
641                            },
642                            None,
643                        )
644                        .await?;
645
646                        Ok(anthropic::extract_tool_args_from_events(
647                            tool_name,
648                            Box::pin(response_lines(response)),
649                        )
650                        .await?
651                        .boxed())
652                    })
653                    .boxed()
654            }
655            CloudModel::OpenAi(model) => {
656                let mut request =
657                    request.into_open_ai(model.id().into(), model.max_output_tokens());
658                request.tool_choice = Some(open_ai::ToolChoice::Other(
659                    open_ai::ToolDefinition::Function {
660                        function: open_ai::FunctionDefinition {
661                            name: tool_name.clone(),
662                            description: None,
663                            parameters: None,
664                        },
665                    },
666                ));
667                request.tools = vec![open_ai::ToolDefinition::Function {
668                    function: open_ai::FunctionDefinition {
669                        name: tool_name.clone(),
670                        description: Some(tool_description),
671                        parameters: Some(input_schema),
672                    },
673                }];
674
675                self.request_limiter
676                    .run(async move {
677                        let response = Self::perform_llm_completion(
678                            client.clone(),
679                            llm_api_token,
680                            PerformCompletionParams {
681                                provider: client::LanguageModelProvider::OpenAi,
682                                model: request.model.clone(),
683                                provider_request: RawValue::from_string(serde_json::to_string(
684                                    &request,
685                                )?)?,
686                            },
687                            None,
688                        )
689                        .await?;
690
691                        Ok(open_ai::extract_tool_args_from_events(
692                            tool_name,
693                            Box::pin(response_lines(response)),
694                        )
695                        .await?
696                        .boxed())
697                    })
698                    .boxed()
699            }
700            CloudModel::Google(_) => {
701                future::ready(Err(anyhow!("tool use not implemented for Google AI"))).boxed()
702            }
703        }
704    }
705}
706
707fn response_lines<T: DeserializeOwned>(
708    response: Response<AsyncBody>,
709) -> impl Stream<Item = Result<T>> {
710    futures::stream::try_unfold(
711        (String::new(), BufReader::new(response.into_body())),
712        move |(mut line, mut body)| async {
713            match body.read_line(&mut line).await {
714                Ok(0) => Ok(None),
715                Ok(_) => {
716                    let event: T = serde_json::from_str(&line)?;
717                    line.clear();
718                    Ok(Some((event, (line, body))))
719                }
720                Err(e) => Err(e.into()),
721            }
722        },
723    )
724}
725
726impl LlmApiToken {
727    async fn acquire(&self, client: &Arc<Client>) -> Result<String> {
728        let lock = self.0.upgradable_read().await;
729        if let Some(token) = lock.as_ref() {
730            Ok(token.to_string())
731        } else {
732            Self::fetch(RwLockUpgradableReadGuard::upgrade(lock).await, client).await
733        }
734    }
735
736    async fn refresh(&self, client: &Arc<Client>) -> Result<String> {
737        Self::fetch(self.0.write().await, client).await
738    }
739
740    async fn fetch<'a>(
741        mut lock: RwLockWriteGuard<'a, Option<String>>,
742        client: &Arc<Client>,
743    ) -> Result<String> {
744        let response = client.request(proto::GetLlmToken {}).await?;
745        *lock = Some(response.token.clone());
746        Ok(response.token.clone())
747    }
748}
749
750struct ConfigurationView {
751    state: gpui::Model<State>,
752}
753
754impl ConfigurationView {
755    fn authenticate(&mut self, cx: &mut ViewContext<Self>) {
756        self.state.update(cx, |state, cx| {
757            state.authenticate(cx).detach_and_log_err(cx);
758        });
759        cx.notify();
760    }
761
762    fn render_accept_terms(&mut self, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
763        if self.state.read(cx).has_accepted_terms_of_service(cx) {
764            return None;
765        }
766
767        let accept_terms_disabled = self.state.read(cx).accept_terms.is_some();
768
769        let terms_button = Button::new("terms_of_service", "Terms of Service")
770            .style(ButtonStyle::Subtle)
771            .icon(IconName::ExternalLink)
772            .icon_color(Color::Muted)
773            .on_click(move |_, cx| cx.open_url("https://zed.dev/terms-of-service"));
774
775        let text =
776            "In order to use Zed AI, please read and accept our terms and conditions to continue:";
777
778        let form = v_flex()
779            .gap_2()
780            .child(Label::new("Terms and Conditions"))
781            .child(Label::new(text))
782            .child(h_flex().justify_center().child(terms_button))
783            .child(
784                h_flex().justify_center().child(
785                    Button::new("accept_terms", "I've read and accept the terms of service")
786                        .style(ButtonStyle::Tinted(TintColor::Accent))
787                        .disabled(accept_terms_disabled)
788                        .on_click({
789                            let state = self.state.downgrade();
790                            move |_, cx| {
791                                state
792                                    .update(cx, |state, cx| state.accept_terms_of_service(cx))
793                                    .ok();
794                            }
795                        }),
796                ),
797            );
798
799        Some(form.into_any())
800    }
801}
802
803impl Render for ConfigurationView {
804    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
805        const ZED_AI_URL: &str = "https://zed.dev/ai";
806        const ACCOUNT_SETTINGS_URL: &str = "https://zed.dev/account";
807
808        let is_connected = !self.state.read(cx).is_signed_out();
809        let plan = self.state.read(cx).user_store.read(cx).current_plan();
810        let has_accepted_terms = self.state.read(cx).has_accepted_terms_of_service(cx);
811
812        let is_pro = plan == Some(proto::Plan::ZedPro);
813        let subscription_text = Label::new(if is_pro {
814            "You have full access to Zed's hosted models from Anthropic, OpenAI, Google with faster speeds and higher limits through Zed Pro."
815        } else {
816            "You have basic access to models from Anthropic through the Zed AI Free plan."
817        });
818        let manage_subscription_button = if is_pro {
819            Some(
820                h_flex().child(
821                    Button::new("manage_settings", "Manage Subscription")
822                        .style(ButtonStyle::Tinted(TintColor::Accent))
823                        .on_click(cx.listener(|_, _, cx| cx.open_url(ACCOUNT_SETTINGS_URL))),
824                ),
825            )
826        } else if cx.has_flag::<ZedPro>() {
827            Some(
828                h_flex()
829                    .gap_2()
830                    .child(
831                        Button::new("learn_more", "Learn more")
832                            .style(ButtonStyle::Subtle)
833                            .on_click(cx.listener(|_, _, cx| cx.open_url(ZED_AI_URL))),
834                    )
835                    .child(
836                        Button::new("upgrade", "Upgrade")
837                            .style(ButtonStyle::Subtle)
838                            .color(Color::Accent)
839                            .on_click(cx.listener(|_, _, cx| cx.open_url(ACCOUNT_SETTINGS_URL))),
840                    ),
841            )
842        } else {
843            None
844        };
845
846        if is_connected {
847            v_flex()
848                .gap_3()
849                .max_w_4_5()
850                .children(self.render_accept_terms(cx))
851                .when(has_accepted_terms, |this| {
852                    this.child(subscription_text)
853                        .children(manage_subscription_button)
854                })
855        } else {
856            v_flex()
857                .gap_6()
858                .child(Label::new("Use the zed.dev to access language models."))
859                .child(
860                    v_flex()
861                        .gap_2()
862                        .child(
863                            Button::new("sign_in", "Sign in")
864                                .icon_color(Color::Muted)
865                                .icon(IconName::Github)
866                                .icon_position(IconPosition::Start)
867                                .style(ButtonStyle::Filled)
868                                .full_width()
869                                .on_click(cx.listener(move |this, _, cx| this.authenticate(cx))),
870                        )
871                        .child(
872                            div().flex().w_full().items_center().child(
873                                Label::new("Sign in to enable collaboration.")
874                                    .color(Color::Muted)
875                                    .size(LabelSize::Small),
876                            ),
877                        ),
878                )
879        }
880    }
881}