feature_flags.rs

  1use futures::channel::oneshot;
  2use futures::{FutureExt, select_biased};
  3use gpui::{App, Context, Global, Subscription, Task, Window};
  4use std::cell::RefCell;
  5use std::rc::Rc;
  6use std::sync::LazyLock;
  7use std::time::Duration;
  8use std::{future::Future, pin::Pin, task::Poll};
  9
 10#[derive(Default)]
 11struct FeatureFlags {
 12    flags: Vec<String>,
 13    staff: bool,
 14}
 15
 16pub static ZED_DISABLE_STAFF: LazyLock<bool> = LazyLock::new(|| {
 17    std::env::var("ZED_DISABLE_STAFF").is_ok_and(|value| !value.is_empty() && value != "0")
 18});
 19
 20impl FeatureFlags {
 21    fn has_flag<T: FeatureFlag>(&self) -> bool {
 22        if T::enabled_for_all() {
 23            return true;
 24        }
 25
 26        if self.staff && T::enabled_for_staff() {
 27            return true;
 28        }
 29
 30        self.flags.iter().any(|f| f.as_str() == T::NAME)
 31    }
 32}
 33
 34impl Global for FeatureFlags {}
 35
 36/// To create a feature flag, implement this trait on a trivial type and use it as
 37/// a generic parameter when called [`FeatureFlagAppExt::has_flag`].
 38///
 39/// Feature flags are enabled for members of Zed staff by default. To disable this behavior
 40/// so you can test flags being disabled, set ZED_DISABLE_STAFF=1 in your environment,
 41/// which will force Zed to treat the current user as non-staff.
 42pub trait FeatureFlag {
 43    const NAME: &'static str;
 44
 45    /// Returns whether this feature flag is enabled for Zed staff.
 46    fn enabled_for_staff() -> bool {
 47        true
 48    }
 49
 50    /// Returns whether this feature flag is enabled for everyone.
 51    ///
 52    /// This is generally done on the server, but we provide this as a way to entirely enable a feature flag client-side
 53    /// without needing to remove all of the call sites.
 54    fn enabled_for_all() -> bool {
 55        false
 56    }
 57}
 58
 59pub struct PredictEditsRateCompletionsFeatureFlag;
 60impl FeatureFlag for PredictEditsRateCompletionsFeatureFlag {
 61    const NAME: &'static str = "predict-edits-rate-completions";
 62}
 63
 64pub struct LlmClosedBetaFeatureFlag {}
 65impl FeatureFlag for LlmClosedBetaFeatureFlag {
 66    const NAME: &'static str = "llm-closed-beta";
 67}
 68
 69pub struct ZedProFeatureFlag {}
 70impl FeatureFlag for ZedProFeatureFlag {
 71    const NAME: &'static str = "zed-pro";
 72}
 73
 74pub struct NotebookFeatureFlag;
 75
 76impl FeatureFlag for NotebookFeatureFlag {
 77    const NAME: &'static str = "notebooks";
 78}
 79
 80pub struct PanicFeatureFlag;
 81
 82impl FeatureFlag for PanicFeatureFlag {
 83    const NAME: &'static str = "panic";
 84}
 85
 86pub struct JjUiFeatureFlag {}
 87
 88impl FeatureFlag for JjUiFeatureFlag {
 89    const NAME: &'static str = "jj-ui";
 90}
 91
 92pub struct GeminiAndNativeFeatureFlag;
 93
 94impl FeatureFlag for GeminiAndNativeFeatureFlag {
 95    // This was previously called "acp".
 96    //
 97    // We renamed it because existing builds used it to enable the Claude Code
 98    // integration too, and we'd like to turn Gemini/Native on in new builds
 99    // without enabling Claude Code in old builds.
100    const NAME: &'static str = "gemini-and-native";
101
102    fn enabled_for_all() -> bool {
103        true
104    }
105}
106
107pub struct ClaudeCodeFeatureFlag;
108
109impl FeatureFlag for ClaudeCodeFeatureFlag {
110    const NAME: &'static str = "claude-code";
111
112    fn enabled_for_all() -> bool {
113        true
114    }
115}
116
117pub trait FeatureFlagViewExt<V: 'static> {
118    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
119    where
120        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
121
122    fn when_flag_enabled<T: FeatureFlag>(
123        &mut self,
124        window: &mut Window,
125        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
126    );
127}
128
129impl<V> FeatureFlagViewExt<V> for Context<'_, V>
130where
131    V: 'static,
132{
133    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
134    where
135        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + 'static,
136    {
137        self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
138            let feature_flags = cx.global::<FeatureFlags>();
139            callback(feature_flags.has_flag::<T>(), v, window, cx);
140        })
141    }
142
143    fn when_flag_enabled<T: FeatureFlag>(
144        &mut self,
145        window: &mut Window,
146        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
147    ) {
148        if self
149            .try_global::<FeatureFlags>()
150            .is_some_and(|f| f.has_flag::<T>())
151        {
152            self.defer_in(window, move |view, window, cx| {
153                callback(view, window, cx);
154            });
155            return;
156        }
157        let subscription = Rc::new(RefCell::new(None));
158        let inner = self.observe_global_in::<FeatureFlags>(window, {
159            let subscription = subscription.clone();
160            move |v, window, cx| {
161                let feature_flags = cx.global::<FeatureFlags>();
162                if feature_flags.has_flag::<T>() {
163                    callback(v, window, cx);
164                    subscription.take();
165                }
166            }
167        });
168        subscription.borrow_mut().replace(inner);
169    }
170}
171
172#[derive(Debug)]
173pub struct OnFlagsReady {
174    pub is_staff: bool,
175}
176
177pub trait FeatureFlagAppExt {
178    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
179
180    /// Waits for the specified feature flag to resolve, up to the given timeout.
181    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
182
183    fn update_flags(&mut self, staff: bool, flags: Vec<String>);
184    fn set_staff(&mut self, staff: bool);
185    fn has_flag<T: FeatureFlag>(&self) -> bool;
186    fn is_staff(&self) -> bool;
187
188    fn on_flags_ready<F>(&mut self, callback: F) -> Subscription
189    where
190        F: FnMut(OnFlagsReady, &mut App) + 'static;
191
192    fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
193    where
194        F: FnMut(bool, &mut App) + 'static;
195}
196
197impl FeatureFlagAppExt for App {
198    fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
199        let feature_flags = self.default_global::<FeatureFlags>();
200        feature_flags.staff = staff;
201        feature_flags.flags = flags;
202    }
203
204    fn set_staff(&mut self, staff: bool) {
205        let feature_flags = self.default_global::<FeatureFlags>();
206        feature_flags.staff = staff;
207    }
208
209    fn has_flag<T: FeatureFlag>(&self) -> bool {
210        self.try_global::<FeatureFlags>()
211            .map(|flags| flags.has_flag::<T>())
212            .unwrap_or(T::enabled_for_all())
213    }
214
215    fn is_staff(&self) -> bool {
216        self.try_global::<FeatureFlags>()
217            .map(|flags| flags.staff)
218            .unwrap_or(false)
219    }
220
221    fn on_flags_ready<F>(&mut self, mut callback: F) -> Subscription
222    where
223        F: FnMut(OnFlagsReady, &mut App) + 'static,
224    {
225        self.observe_global::<FeatureFlags>(move |cx| {
226            let feature_flags = cx.global::<FeatureFlags>();
227            callback(
228                OnFlagsReady {
229                    is_staff: feature_flags.staff,
230                },
231                cx,
232            );
233        })
234    }
235
236    fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
237    where
238        F: FnMut(bool, &mut App) + 'static,
239    {
240        self.observe_global::<FeatureFlags>(move |cx| {
241            let feature_flags = cx.global::<FeatureFlags>();
242            callback(feature_flags.has_flag::<T>(), cx);
243        })
244    }
245
246    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
247        let (tx, rx) = oneshot::channel::<bool>();
248        let mut tx = Some(tx);
249        let subscription: Option<Subscription>;
250
251        match self.try_global::<FeatureFlags>() {
252            Some(feature_flags) => {
253                subscription = None;
254                tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
255            }
256            None => {
257                subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
258                    let feature_flags = cx.global::<FeatureFlags>();
259                    if let Some(tx) = tx.take() {
260                        tx.send(feature_flags.has_flag::<T>()).ok();
261                    }
262                }));
263            }
264        }
265
266        WaitForFlag(rx, subscription)
267    }
268
269    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
270        let wait_for_flag = self.wait_for_flag::<T>();
271
272        self.spawn(async move |_cx| {
273            let mut wait_for_flag = wait_for_flag.fuse();
274            let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
275
276            select_biased! {
277                is_enabled = wait_for_flag => is_enabled,
278                _ = timeout => false,
279            }
280        })
281    }
282}
283
284pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
285
286impl Future for WaitForFlag {
287    type Output = bool;
288
289    fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
290        self.0.poll_unpin(cx).map(|result| {
291            self.1.take();
292            result.unwrap_or(false)
293        })
294    }
295}