Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Fix edit predictions for organizations without a subscription (#65301)
morgankrey129c68ff4bc1
diff --git a/crates/client/src/user.rs b/crates/client/src/user.rsindex 1d8c2693c4f..3513bd59611 100644--- a/crates/client/src/user.rs+++ b/crates/client/src/user.rs@@ -793,6 +793,17 @@ impl UserStore {self.plan_info.as_ref().map(|info| info.plan())}+ pub fn current_organization_has_no_active_subscription(&self) -> bool {+ self.plan_info.is_some()+ && self+ .current_organization+ .as_ref()+ .is_some_and(|organization| {+ !organization.is_personal+ && !self.plans_by_organization.contains_key(&organization.id)+ })+ }+pub fn subscription_period(&self) -> Option<(DateTime<Utc>, DateTime<Utc>)> {self.plan_info.as_ref()@@ -1099,3 +1110,73 @@ impl EditPredictionUsage {)?))}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::test::make_get_authenticated_user_response;+ use clock::FakeSystemClock;+ use gpui::TestAppContext;+ use http_client::FakeHttpClient;+ use settings::SettingsStore;++ #[gpui::test]+ async fn test_current_organization_has_no_active_subscription(cx: &mut TestAppContext) {+ cx.update(|cx| {+ let settings_store = SettingsStore::test(cx);+ cx.set_global(settings_store);+ });+ let client = cx.update(|cx| {+ Client::new(+ Arc::new(FakeSystemClock::new()),+ FakeHttpClient::with_404_response(),+ cx,+ )+ });+ let user_store = cx.new(|cx| UserStore::new(client, cx));++ let organization = |id: &str, is_personal| Organization {+ id: OrganizationId(id.into()),+ name: id.into(),+ is_personal,+ };++ assert!(!user_store.read_with(cx, |store, _| {+ store.current_organization_has_no_active_subscription()+ }));++ user_store.update(cx, |store, cx| {+ let mut response = make_get_authenticated_user_response(1, "user".into());+ response.organizations = vec![+ organization("personal", true),+ organization("unsubscribed", false),+ organization("paid", false),+ ];+ response.default_organization_id = Some(OrganizationId("unsubscribed".into()));+ response.plans_by_organization.insert(+ OrganizationId("personal".into()),+ KnownOrUnknown::Known(Plan::ZedPro),+ );+ response.plans_by_organization.insert(+ OrganizationId("paid".into()),+ KnownOrUnknown::Known(Plan::ZedBusiness),+ );+ store.update_authenticated_user(response, cx);+ });+ assert!(user_store.read_with(cx, |store, _| {+ store.current_organization_has_no_active_subscription()+ }));++ for organization in [organization("personal", true), organization("paid", false)] {+ user_store+ .update(cx, |store, cx| {+ store.set_current_organization(Arc::new(organization), cx)+ })+ .await+ .unwrap();+ assert!(!user_store.read_with(cx, |store, _| {+ store.current_organization_has_no_active_subscription()+ }));+ }+ }+}diff --git a/crates/edit_prediction/src/edit_prediction.rs b/crates/edit_prediction/src/edit_prediction.rsindex d7cb3fc7e7f..0c85fa0f595 100644--- a/crates/edit_prediction/src/edit_prediction.rs+++ b/crates/edit_prediction/src/edit_prediction.rs@@ -2796,6 +2796,16 @@ impl EditPredictionStore {return Task::ready(Ok(None));}+ // Cloud rejects these requests too; skipping them avoids futile round trips.+ if is_cloud_zeta+ && self+ .user_store+ .read(cx)+ .current_organization_has_no_active_subscription()+ {+ return Task::ready(Ok(None));+ }+if is_cloud_zeta && self.request_backoff_active(cx) {log::debug!("Skipping Zeta edit prediction request while backing off after Cloud timeout"diff --git a/crates/edit_prediction/src/edit_prediction_tests.rs b/crates/edit_prediction/src/edit_prediction_tests.rsindex a2435318e05..2d05d04f85a 100644--- a/crates/edit_prediction/src/edit_prediction_tests.rs+++ b/crates/edit_prediction/src/edit_prediction_tests.rs@@ -1,8 +1,11 @@-use client::{RefreshLlmTokenListener, UserStore, test::FakeServer};+use client::{+ Credentials, RefreshLlmTokenListener, UserStore,+ test::{FakeServer, make_get_authenticated_user_response},+};use clock::FakeSystemClock;use clock::ReplicaId;use cloud_api_types::{- CreateLlmTokenResponse, LlmToken, Organization, OrganizationConfiguration,+ CreateLlmTokenResponse, KnownOrUnknown, LlmToken, Organization, OrganizationConfiguration,OrganizationEditPredictionConfiguration, OrganizationId, Plan, SettledEditPrediction,SubmitEditPredictionSettledBatchBody, SubmitEditPredictionSettledResponse,};@@ -2216,6 +2219,137 @@ async fn test_cloud_timeout_backs_off_zeta_requests(cx: &mut TestAppContext) {cx.run_until_parked();}+#[gpui::test]+async fn test_zed_cloud_predictions_skip_organizations_without_subscriptions(+ cx: &mut TestAppContext,+) {+ let (ep_store, mut requests) = init_test_with_fake_client(cx);+ let fs = FakeFs::new(cx.executor());+ fs.insert_tree("/root", json!({ "foo.md": "Hello!\nHow\nBye\n" }))+ .await;+ let project = Project::test(fs, vec![path!("/root").as_ref()], cx).await;+ let buffer = project+ .update(cx, |project, cx| {+ let path = project.find_project_path(path!("root/foo.md"), cx).unwrap();+ project.open_buffer(path, cx)+ })+ .await+ .unwrap();+ let position = buffer+ .read_with(cx, |buffer, _cx| buffer.snapshot())+ .anchor_before(language::Point::new(1, 3));+ let request_prediction = |ep_store: &Entity<EditPredictionStore>, cx: &mut TestAppContext| {+ ep_store.update(cx, |ep_store, cx| {+ ep_store.request_prediction(+ &project,+ &buffer,+ position,+ PredictEditsRequestTrigger::Other,+ cx,+ )+ })+ };++ let organization = |id: &str| Organization {+ id: OrganizationId(id.into()),+ name: id.into(),+ is_personal: false,+ };+ let mut authenticated_user = make_get_authenticated_user_response(1, "user".into());+ authenticated_user.organizations = vec![organization("unsubscribed"), organization("paid")];+ authenticated_user.plans_by_organization.insert(+ OrganizationId("paid".into()),+ KnownOrUnknown::Known(Plan::ZedBusiness),+ );+ let authenticated_user = serde_json::to_string(&authenticated_user).unwrap();+ let local_completion_requests = Arc::new(Mutex::new(0));+ let client = ep_store.read_with(cx, |ep_store, _cx| ep_store.client.clone());+ client.http_client().as_fake().replace_handler({+ let local_completion_requests = local_completion_requests.clone();+ move |old_handler, request| {+ let authenticated_user = authenticated_user.clone();+ let local_completion_requests = local_completion_requests.clone();+ async move {+ let body = match request.uri().path() {+ "/client/users/me" => authenticated_user,+ "/v1/completions" => {+ *local_completion_requests.lock() += 1;+ serde_json::to_string(&RawCompletionResponse {+ id: "local".into(),+ object: "text_completion".into(),+ created: 0,+ model: "local".into(),+ choices: vec![RawCompletionChoice {+ text: String::new(),+ finish_reason: Some("stop".into()),+ }],+ usage: RawCompletionUsage {+ prompt_tokens: 0,+ completion_tokens: 0,+ total_tokens: 0,+ },+ })+ .unwrap()+ }+ _ => return old_handler(request).await,+ };+ Ok(Response::builder().body(body.into()).unwrap())+ }+ }+ });+ client.override_authenticate(|_| {+ Task::ready(Ok(Credentials {+ user_id: 1,+ access_token: "test".into(),+ }))+ });+ client.sign_in(false, &cx.to_async()).await.unwrap();+ cx.run_until_parked();++ let blocked_request = request_prediction(&ep_store, cx);+ cx.run_until_parked();+ assert_no_predict_request_ready(&mut requests.predict);+ assert!(matches!(blocked_request.now_or_never(), Some(Ok(None))));++ let set_provider = |provider, cx: &mut TestAppContext| {+ cx.update_global::<SettingsStore, _>(|settings_store, cx| {+ settings_store.update_user_settings(cx, |settings| {+ let edit_predictions = settings+ .project+ .all_languages+ .edit_predictions+ .get_or_insert_default();+ edit_predictions.provider = Some(provider);+ edit_predictions.open_ai_compatible_api =+ Some(settings::CustomEditPredictionProviderSettingsContent {+ api_url: Some("http://localhost:8080/v1/completions".into()),+ model: Some("local".into()),+ prompt_format: Some(settings::EditPredictionPromptFormatContent::Zeta2),+ max_output_tokens: Some(64),+ prediction_debounce: None,+ });+ });+ });+ };+ cx.update(|cx| cx.set_http_client(client.http_client()));+ set_provider(settings::EditPredictionProvider::OpenAiCompatibleApi, cx);+ request_prediction(&ep_store, cx).await.unwrap();+ assert_eq!(*local_completion_requests.lock(), 1);+ set_provider(settings::EditPredictionProvider::Zed, cx);++ let user_store = ep_store.read_with(cx, |ep_store, _cx| ep_store.user_store.clone());+ user_store+ .update(cx, |user_store, cx| {+ user_store.set_current_organization(Arc::new(organization("paid")), cx)+ })+ .await+ .unwrap();+ let paid_request = request_prediction(&ep_store, cx);+ let (_, paid_response) = requests.predict.next().await.unwrap();+ paid_response.send(empty_response()).unwrap();+ paid_request.await.unwrap();+}+#[gpui::test]async fn test_same_frame_duplicate_requests_deduplicated(cx: &mut TestAppContext) {let (ep_store, mut requests) = init_test_with_fake_client(cx);diff --git a/crates/edit_prediction_ui/src/edit_prediction_button.rs b/crates/edit_prediction_ui/src/edit_prediction_button.rsindex 2a96d9c1f5b..a9eb5733cbb 100644--- a/crates/edit_prediction_ui/src/edit_prediction_button.rs+++ b/crates/edit_prediction_ui/src/edit_prediction_button.rs@@ -433,6 +433,12 @@ impl Render for EditPredictionButton {let show_editor_predictions = self.editor_show_predictions;let user = self.user_store.read(cx).current_user();+ let zed_cloud_has_no_active_subscription =+ matches!(provider, EditPredictionProvider::Zed)+ && self+ .user_store+ .read(cx)+ .current_organization_has_no_active_subscription();let excluded_from_plan = edit_prediction::zed_edit_predictions_excluded_from_plan(self.user_store.read(cx),cx,@@ -443,24 +449,27 @@ impl Render for EditPredictionButton {|ep_store| ep_store.read(cx).mercury_has_payment_required_error(),);- let indicator_color = if missing_token || mercury_has_error {- Some(Color::Error)- } else if excluded_from_plan {- Some(Color::Muted)- } else if enabled && (!show_editor_predictions || over_limit) {- Some(if over_limit {- Color::Error+ let indicator_color =+ if missing_token || mercury_has_error || zed_cloud_has_no_active_subscription {+ Some(Color::Error)+ } else if excluded_from_plan {+ Some(Color::Muted)+ } else if enabled && (!show_editor_predictions || over_limit) {+ Some(if over_limit {+ Color::Error+ } else {+ Color::Muted+ })} else {- Color::Muted- })- } else {- None- };+ None+ };let zed_cloud_needs_sign_in =matches!(provider, EditPredictionProvider::Zed) && user.is_none();- let provider_unavailable =- missing_token || mercury_has_error || zed_cloud_needs_sign_in;+ let provider_unavailable = missing_token+ || mercury_has_error+ || zed_cloud_needs_sign_in+ || zed_cloud_has_no_active_subscription;let icon_button = IconButton::new("zed-predict-pending-button", ep_icon).shape(IconButtonShape::Square)@@ -476,6 +485,8 @@ impl Render for EditPredictionButton {"Disabled For This File"} else if zed_cloud_needs_sign_in {"Sign In Or Configure a Provider"+ } else if zed_cloud_has_no_active_subscription {+ "This organization has no active subscription"} else if excluded_from_plan {"Configure a Provider"} else if provider_unavailable || show_editor_predictions {@@ -570,6 +581,8 @@ impl EditPredictionButton {cx.observe_global::<EditPredictionStore>(move |_, cx| cx.notify()).detach();+ cx.observe(&user_store, |_, _, cx| cx.notify()).detach();+let mercury_api_token_task = edit_prediction::mercury::load_mercury_api_token(cx);let open_ai_compatible_api_token_task =edit_prediction::open_ai_compatible::load_open_ai_compatible_api_token(cx);@@ -1021,22 +1034,34 @@ impl EditPredictionButton {}if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {+ let zed_cloud_has_no_active_subscription =+ all_language_settings(None, cx).edit_predictions.provider+ == EditPredictionProvider::Zed+ && self+ .user_store+ .read(cx)+ .current_organization_has_no_active_subscription();menu = menu.separator().header("Actions")- .entry(- "Predict Edit at Cursor",- Some(Box::new(ShowEditPrediction)),- {- let editor_focus_handle = editor_focus_handle.clone();- move |window, cx| {- telemetry::event!(- "Edit Prediction Menu Action",- action = "predict_at_cursor",- );- editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);- }- },+ .item(+ ContextMenuEntry::new("Predict Edit at Cursor")+ .action(Box::new(ShowEditPrediction))+ .disabled(zed_cloud_has_no_active_subscription)+ .handler({+ let editor_focus_handle = editor_focus_handle.clone();+ move |window, cx| {+ telemetry::event!(+ "Edit Prediction Menu Action",+ action = "predict_at_cursor",+ );+ editor_focus_handle.dispatch_action(+ &ShowEditPrediction,+ window,+ cx,+ );+ }+ }),).context(editor_focus_handle).when(@@ -1208,7 +1233,30 @@ impl EditPredictionButton {.separator();}- if edit_prediction::zed_edit_predictions_excluded_from_plan(+ let zed_cloud_has_no_active_subscription =+ matches!(provider, EditPredictionProvider::Zed)+ && self+ .user_store+ .read(cx)+ .current_organization_has_no_active_subscription();++ if zed_cloud_has_no_active_subscription {+ menu = menu+ .header("Zed AI")+ .item(+ ContextMenuEntry::new(+ "This organization has no active subscription",+ )+ .disabled(true),+ )+ .item(+ ContextMenuEntry::new(+ "Switch organizations or configure another provider to use edit predictions",+ )+ .disabled(true),+ )+ .separator();+ } else if edit_prediction::zed_edit_predictions_excluded_from_plan(self.user_store.read(cx),cx,) {