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").map_or(false, |value| !value.is_empty() && value != "0")
 18});
 19
 20impl FeatureFlags {
 21    fn has_flag<T: FeatureFlag>(&self) -> bool {
 22        if self.staff && T::enabled_for_staff() {
 23            return true;
 24        }
 25
 26        #[cfg(debug_assertions)]
 27        if T::enabled_in_development() {
 28            return true;
 29        }
 30
 31        self.flags.iter().any(|f| f.as_str() == T::NAME)
 32    }
 33}
 34
 35impl Global for FeatureFlags {}
 36
 37/// To create a feature flag, implement this trait on a trivial type and use it as
 38/// a generic parameter when called [`FeatureFlagAppExt::has_flag`].
 39///
 40/// Feature flags are enabled for members of Zed staff by default. To disable this behavior
 41/// so you can test flags being disabled, set ZED_DISABLE_STAFF=1 in your environment,
 42/// which will force Zed to treat the current user as non-staff.
 43pub trait FeatureFlag {
 44    const NAME: &'static str;
 45
 46    /// Returns whether this feature flag is enabled for Zed staff.
 47    fn enabled_for_staff() -> bool {
 48        true
 49    }
 50
 51    fn enabled_in_development() -> bool {
 52        Self::enabled_for_staff() && !*ZED_DISABLE_STAFF
 53    }
 54}
 55
 56pub struct Assistant2FeatureFlag;
 57
 58impl FeatureFlag for Assistant2FeatureFlag {
 59    const NAME: &'static str = "assistant2";
 60}
 61
 62pub struct PredictEditsRateCompletionsFeatureFlag;
 63impl FeatureFlag for PredictEditsRateCompletionsFeatureFlag {
 64    const NAME: &'static str = "predict-edits-rate-completions";
 65}
 66
 67pub struct Remoting {}
 68impl FeatureFlag for Remoting {
 69    const NAME: &'static str = "remoting";
 70}
 71
 72pub struct LanguageModels {}
 73impl FeatureFlag for LanguageModels {
 74    const NAME: &'static str = "language-models";
 75}
 76
 77pub struct LlmClosedBeta {}
 78impl FeatureFlag for LlmClosedBeta {
 79    const NAME: &'static str = "llm-closed-beta";
 80}
 81
 82pub struct ZedPro {}
 83impl FeatureFlag for ZedPro {
 84    const NAME: &'static str = "zed-pro";
 85}
 86
 87pub struct NotebookFeatureFlag;
 88
 89impl FeatureFlag for NotebookFeatureFlag {
 90    const NAME: &'static str = "notebooks";
 91}
 92
 93pub struct Debugger {}
 94impl FeatureFlag for Debugger {
 95    const NAME: &'static str = "debugger";
 96}
 97
 98pub trait FeatureFlagViewExt<V: 'static> {
 99    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
100    where
101        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
102
103    fn when_flag_enabled<T: FeatureFlag>(
104        &mut self,
105        window: &mut Window,
106        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
107    );
108}
109
110impl<V> FeatureFlagViewExt<V> for Context<'_, V>
111where
112    V: 'static,
113{
114    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
115    where
116        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + 'static,
117    {
118        self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
119            let feature_flags = cx.global::<FeatureFlags>();
120            callback(feature_flags.has_flag::<T>(), v, window, cx);
121        })
122    }
123
124    fn when_flag_enabled<T: FeatureFlag>(
125        &mut self,
126        window: &mut Window,
127        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
128    ) {
129        if self
130            .try_global::<FeatureFlags>()
131            .is_some_and(|f| f.has_flag::<T>())
132            || cfg!(debug_assertions) && T::enabled_in_development()
133        {
134            self.defer_in(window, move |view, window, cx| {
135                callback(view, window, cx);
136            });
137            return;
138        }
139        let subscription = Rc::new(RefCell::new(None));
140        let inner = self.observe_global_in::<FeatureFlags>(window, {
141            let subscription = subscription.clone();
142            move |v, window, cx| {
143                let feature_flags = cx.global::<FeatureFlags>();
144                if feature_flags.has_flag::<T>() {
145                    callback(v, window, cx);
146                    subscription.take();
147                }
148            }
149        });
150        subscription.borrow_mut().replace(inner);
151    }
152}
153
154pub trait FeatureFlagAppExt {
155    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
156
157    /// Waits for the specified feature flag to resolve, up to the given timeout.
158    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
159
160    fn update_flags(&mut self, staff: bool, flags: Vec<String>);
161    fn set_staff(&mut self, staff: bool);
162    fn has_flag<T: FeatureFlag>(&self) -> bool;
163    fn is_staff(&self) -> bool;
164
165    fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
166    where
167        F: FnMut(bool, &mut App) + 'static;
168}
169
170impl FeatureFlagAppExt for App {
171    fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
172        let feature_flags = self.default_global::<FeatureFlags>();
173        feature_flags.staff = staff;
174        feature_flags.flags = flags;
175    }
176
177    fn set_staff(&mut self, staff: bool) {
178        let feature_flags = self.default_global::<FeatureFlags>();
179        feature_flags.staff = staff;
180    }
181
182    fn has_flag<T: FeatureFlag>(&self) -> bool {
183        self.try_global::<FeatureFlags>()
184            .map(|flags| flags.has_flag::<T>())
185            .unwrap_or(false)
186    }
187
188    fn is_staff(&self) -> bool {
189        self.try_global::<FeatureFlags>()
190            .map(|flags| flags.staff)
191            .unwrap_or(false)
192    }
193
194    fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
195    where
196        F: FnMut(bool, &mut App) + 'static,
197    {
198        self.observe_global::<FeatureFlags>(move |cx| {
199            let feature_flags = cx.global::<FeatureFlags>();
200            callback(feature_flags.has_flag::<T>(), cx);
201        })
202    }
203
204    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
205        let (tx, rx) = oneshot::channel::<bool>();
206        let mut tx = Some(tx);
207        let subscription: Option<Subscription>;
208
209        match self.try_global::<FeatureFlags>() {
210            Some(feature_flags) => {
211                subscription = None;
212                tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
213            }
214            None => {
215                subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
216                    let feature_flags = cx.global::<FeatureFlags>();
217                    if let Some(tx) = tx.take() {
218                        tx.send(feature_flags.has_flag::<T>()).ok();
219                    }
220                }));
221            }
222        }
223
224        WaitForFlag(rx, subscription)
225    }
226
227    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
228        let wait_for_flag = self.wait_for_flag::<T>();
229
230        self.spawn(async move |_cx| {
231            let mut wait_for_flag = wait_for_flag.fuse();
232            let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
233
234            select_biased! {
235                is_enabled = wait_for_flag => is_enabled,
236                _ = timeout => false,
237            }
238        })
239    }
240}
241
242pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
243
244impl Future for WaitForFlag {
245    type Output = bool;
246
247    fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
248        self.0.poll_unpin(cx).map(|result| {
249            self.1.take();
250            result.unwrap_or(false)
251        })
252    }
253}