Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
cloud: Fix incorrect model getting selected at startup (#55325)
Bennet Bo Fenner038e2136fb98
diff --git a/Cargo.lock b/Cargo.lockindex 0c1d7d86736..c4b5068f414 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -9618,6 +9618,7 @@ dependencies = ["base64 0.22.1","bedrock","client",+ "clock","cloud_api_client","cloud_api_types","collections",@@ -9627,9 +9628,11 @@ dependencies = ["copilot_chat","copilot_ui","credentials_provider",+ "db","deepseek","extension","extension_host",+ "feature_flags","fs","futures 0.3.32","google_ai",diff --git a/crates/language_models/Cargo.toml b/crates/language_models/Cargo.tomlindex 8e0216ba6c8..7afcbb8aea1 100644--- a/crates/language_models/Cargo.toml+++ b/crates/language_models/Cargo.toml@@ -64,5 +64,12 @@ util.workspace = truex_ai = { workspace = true, features = ["schemars"] }[dev-dependencies]+client = { workspace = true, features = ["test-support"] }+clock = { workspace = true, features = ["test-support"] }+db = { workspace = true, features = ["test-support"] }+feature_flags.workspace = true+gpui = { workspace = true, features = ["test-support"] }+http_client = { workspace = true, features = ["test-support"] }language_model = { workspace = true, features = ["test-support"] }pretty_assertions.workspace = true+settings = { workspace = true, features = ["test-support"] }diff --git a/crates/language_models/src/provider/cloud.rs b/crates/language_models/src/provider/cloud.rsindex 1c4de9e1afa..0dae88fc307 100644--- a/crates/language_models/src/provider/cloud.rs+++ b/crates/language_models/src/provider/cloud.rs@@ -4,6 +4,7 @@ use client::{Client, RefreshLlmTokenListener, UserStore, global_llm_token, zed_uuse cloud_api_client::LlmApiToken;use cloud_api_types::OrganizationId;use cloud_api_types::Plan;+use futures::FutureExt;use futures::StreamExt;use futures::future::BoxFuture;use gpui::{AnyElement, AnyView, App, AppContext, Context, Entity, Subscription, Task};@@ -147,11 +148,17 @@ impl State {self.user_store.read(cx).current_user().is_none()}- fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<()>> {+ fn sign_in(&self, cx: &mut Context<Self>) -> Task<Result<()>> {let client = self.client.clone();+ let mut current_user = self.user_store.read(cx).watch_current_user();cx.spawn(async move |state, cx| {client.sign_in_with_optional_connect(true, cx).await?;- state.update(cx, |_, cx| cx.notify())+ while current_user.borrow().is_none() {+ current_user.next().await;+ }+ state.update(cx, |_, cx| {+ cx.notify();+ })})}@@ -253,7 +260,11 @@ impl LanguageModelProvider for CloudLanguageModelProvider {}fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {+ if self.is_authenticated(cx) {+ return Task::ready(Ok(()));+ }let mut status = self.state.read(cx).client.status();+ let mut current_user = self.state.read(cx).user_store.read(cx).watch_current_user();if !status.borrow().is_signing_in() {return Task::ready(Ok(()));}@@ -261,6 +272,23 @@ impl LanguageModelProvider for CloudLanguageModelProvider {while status.borrow().is_signing_in() {status.next().await;}+ while current_user.borrow().is_none() {+ let current_status = *status.borrow();+ if !matches!(+ current_status,+ client::Status::Authenticated+ | client::Status::Reauthenticated+ | client::Status::Connected { .. }+ ) {+ return Err(AuthenticateError::Other(anyhow::anyhow!(+ "sign-in did not complete: {current_status:?}"+ )));+ }+ futures::select_biased! {+ _ = current_user.next().fuse() => {},+ _ = status.next().fuse() => {},+ }+ }Ok(())})}@@ -387,7 +415,7 @@ impl ConfigurationView {let state = state.clone();move |_window: &mut Window, cx: &mut App| {state.update(cx, |state, cx| {- state.authenticate(cx).detach_and_log_err(cx);+ state.sign_in(cx).detach_and_log_err(cx);});}});@@ -419,6 +447,211 @@ impl Render for ConfigurationView {}}+#[cfg(test)]+mod tests {+ use super::*;+ use client::{Credentials, test::make_get_authenticated_user_response};+ use clock::FakeSystemClock;+ use feature_flags::FeatureFlagAppExt as _;+ use gpui::TestAppContext;+ use http_client::{FakeHttpClient, Method, Response};+ use std::sync::{+ Arc, Mutex,+ atomic::{AtomicUsize, Ordering},+ };++ const TEST_USER_ID: u64 = 42;++ fn init_test(cx: &mut App) -> (Arc<Client>, Entity<UserStore>, CloudLanguageModelProvider) {+ let settings_store = SettingsStore::test(cx);+ cx.set_global(settings_store);+ cx.set_global(db::AppDatabase::test_new());+ let app_version = AppVersion::global(cx);+ release_channel::init_test(app_version, release_channel::ReleaseChannel::Dev, cx);+ gpui_tokio::init(cx);+ cx.update_flags(false, Vec::new());++ let client = Client::new(+ Arc::new(FakeSystemClock::new()),+ FakeHttpClient::with_404_response(),+ cx,+ );+ let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));+ RefreshLlmTokenListener::register(client.clone(), user_store.clone(), cx);+ let provider = CloudLanguageModelProvider::new(user_store.clone(), client.clone(), cx);++ (client, user_store, provider)+ }++ fn override_authenticate(+ client: &Arc<Client>,+ authenticate_rx: futures::channel::oneshot::Receiver<anyhow::Result<Credentials>>,+ ) {+ let authenticate_rx = Arc::new(Mutex::new(Some(authenticate_rx)));+ client.override_authenticate(move |cx| {+ let authenticate_rx = authenticate_rx.clone();+ cx.background_spawn(async move {+ let authenticate_rx = authenticate_rx+ .lock()+ .expect("authenticate receiver lock poisoned")+ .take()+ .expect("authenticate receiver already used");+ authenticate_rx.await?+ })+ });+ }++ fn respond_to_authenticated_user_after(+ client: &Arc<Client>,+ authenticated_user_rx: futures::channel::oneshot::Receiver<()>,+ ) {+ let authenticated_user_rx = Arc::new(Mutex::new(Some(authenticated_user_rx)));+ client+ .http_client()+ .as_fake()+ .replace_handler(move |old_handler, request| {+ let authenticated_user_rx = authenticated_user_rx.clone();+ async move {+ if request.method() == Method::GET && request.uri().path() == "/client/users/me"+ {+ let authenticated_user_rx = authenticated_user_rx+ .lock()+ .expect("authenticated user receiver lock poisoned")+ .take();+ if let Some(authenticated_user_rx) = authenticated_user_rx {+ authenticated_user_rx.await.ok();+ }++ return Ok(Response::builder()+ .status(200)+ .body(+ serde_json::to_string(&make_get_authenticated_user_response(+ TEST_USER_ID as i32,+ format!("user-{TEST_USER_ID}"),+ ))+ .expect("failed to serialize authenticated user response")+ .into(),+ )+ .expect("failed to build authenticated user response"));+ }++ old_handler(request).await+ }+ });+ }++ async fn sign_in_until_authenticating(+ client: Arc<Client>,+ cx: &mut TestAppContext,+ ) -> Task<anyhow::Result<Credentials>> {+ let mut status = client.status();+ let sign_in_task = cx.update(|cx| {+ cx.spawn({+ let client = client.clone();+ async move |cx| client.sign_in(false, cx).await+ })+ });++ while !status.borrow().is_signing_in() {+ status.next().await;+ }++ sign_in_task+ }++ #[gpui::test]+ async fn provider_authenticate_does_not_start_sign_in_when_signed_out(cx: &mut TestAppContext) {+ let (client, _user_store, provider) = cx.update(init_test);+ let authenticate_calls = Arc::new(AtomicUsize::new(0));+ client.override_authenticate({+ let authenticate_calls = authenticate_calls.clone();+ move |_| {+ authenticate_calls.fetch_add(1, Ordering::SeqCst);+ Task::ready(Err(anyhow::anyhow!(+ "provider authenticate should not start sign-in"+ )))+ }+ });++ assert!(!cx.read(|cx| provider.is_authenticated(cx)));+ assert!(matches!(+ *client.status().borrow(),+ client::Status::SignedOut+ ));++ cx.update(|cx| provider.authenticate(cx))+ .now_or_never()+ .expect("authenticate should return immediately when signed out")+ .expect("authenticate should not fail when no sign-in is in progress");+ cx.executor().run_until_parked();++ assert_eq!(authenticate_calls.load(Ordering::SeqCst), 0);+ assert!(matches!(+ *client.status().borrow(),+ client::Status::SignedOut+ ));+ assert!(!cx.read(|cx| provider.is_authenticated(cx)));+ }++ #[gpui::test]+ async fn provider_authenticate_waits_for_current_user(cx: &mut TestAppContext) {+ let (client, _user_store, provider) = cx.update(init_test);+ let (authenticate_tx, authenticate_rx) = futures::channel::oneshot::channel();+ let (authenticated_user_tx, authenticated_user_rx) = futures::channel::oneshot::channel();+ override_authenticate(&client, authenticate_rx);+ respond_to_authenticated_user_after(&client, authenticated_user_rx);++ let sign_in_task = sign_in_until_authenticating(client.clone(), cx).await;+ let authenticate_task = cx.update(|cx| provider.authenticate(cx));+ authenticate_tx+ .send(Ok(Credentials {+ user_id: TEST_USER_ID,+ access_token: "token".to_string(),+ }))+ .expect("authenticate receiver dropped");++ cx.executor().run_until_parked();+ assert!(!cx.read(|cx| provider.is_authenticated(cx)));++ authenticated_user_tx+ .send(())+ .expect("authenticated user receiver dropped");+ sign_in_task+ .await+ .expect("sign-in should complete after user response");+ authenticate_task+ .await+ .expect("provider authentication should complete after current user is populated");+ assert!(cx.read(|cx| provider.is_authenticated(cx)));++ cx.update(|cx| provider.authenticate(cx))+ .now_or_never()+ .expect("already-authenticated provider should authenticate immediately")+ .unwrap();+ }++ #[gpui::test]+ async fn provider_authenticate_returns_error_when_sign_in_fails(cx: &mut TestAppContext) {+ let (client, _user_store, provider) = cx.update(init_test);+ let (authenticate_tx, authenticate_rx) = futures::channel::oneshot::channel();+ override_authenticate(&client, authenticate_rx);++ let sign_in_task = sign_in_until_authenticating(client.clone(), cx).await;+ let authenticate_task = cx.update(|cx| provider.authenticate(cx));+ authenticate_tx+ .send(Err(anyhow::anyhow!("test authentication failed")))+ .expect("authenticate receiver dropped");++ sign_in_task+ .await+ .expect_err("sign-in should report authentication failure");+ let error = authenticate_task+ .await+ .expect_err("provider authentication should fail when sign-in fails");+ assert!(error.to_string().contains("AuthenticationError"));+ }+}+impl Component for ZedAiConfiguration {fn name() -> &'static str {"AI Configuration Content"