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 LanguageModelsFeatureFlag {}
 68impl FeatureFlag for LanguageModelsFeatureFlag {
 69    const NAME: &'static str = "language-models";
 70}
 71
 72pub struct LlmClosedBetaFeatureFlag {}
 73impl FeatureFlag for LlmClosedBetaFeatureFlag {
 74    const NAME: &'static str = "llm-closed-beta";
 75}
 76
 77pub struct ZedProFeatureFlag {}
 78impl FeatureFlag for ZedProFeatureFlag {
 79    const NAME: &'static str = "zed-pro";
 80}
 81
 82pub struct NotebookFeatureFlag;
 83
 84impl FeatureFlag for NotebookFeatureFlag {
 85    const NAME: &'static str = "notebooks";
 86}
 87
 88pub struct DebuggerFeatureFlag {}
 89impl FeatureFlag for DebuggerFeatureFlag {
 90    const NAME: &'static str = "debugger";
 91}
 92
 93pub struct ThreadAutoCaptureFeatureFlag {}
 94impl FeatureFlag for ThreadAutoCaptureFeatureFlag {
 95    const NAME: &'static str = "thread-auto-capture";
 96
 97    fn enabled_for_staff() -> bool {
 98        false
 99    }
100}
101
102pub trait FeatureFlagViewExt<V: 'static> {
103    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
104    where
105        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
106
107    fn when_flag_enabled<T: FeatureFlag>(
108        &mut self,
109        window: &mut Window,
110        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
111    );
112}
113
114impl<V> FeatureFlagViewExt<V> for Context<'_, V>
115where
116    V: 'static,
117{
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>) + 'static,
121    {
122        self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
123            let feature_flags = cx.global::<FeatureFlags>();
124            callback(feature_flags.has_flag::<T>(), v, window, cx);
125        })
126    }
127
128    fn when_flag_enabled<T: FeatureFlag>(
129        &mut self,
130        window: &mut Window,
131        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
132    ) {
133        if self
134            .try_global::<FeatureFlags>()
135            .is_some_and(|f| f.has_flag::<T>())
136            || cfg!(debug_assertions) && T::enabled_in_development()
137        {
138            self.defer_in(window, move |view, window, cx| {
139                callback(view, window, cx);
140            });
141            return;
142        }
143        let subscription = Rc::new(RefCell::new(None));
144        let inner = self.observe_global_in::<FeatureFlags>(window, {
145            let subscription = subscription.clone();
146            move |v, window, cx| {
147                let feature_flags = cx.global::<FeatureFlags>();
148                if feature_flags.has_flag::<T>() {
149                    callback(v, window, cx);
150                    subscription.take();
151                }
152            }
153        });
154        subscription.borrow_mut().replace(inner);
155    }
156}
157
158pub trait FeatureFlagAppExt {
159    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
160
161    /// Waits for the specified feature flag to resolve, up to the given timeout.
162    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
163
164    fn update_flags(&mut self, staff: bool, flags: Vec<String>);
165    fn set_staff(&mut self, staff: bool);
166    fn has_flag<T: FeatureFlag>(&self) -> bool;
167    fn is_staff(&self) -> bool;
168
169    fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
170    where
171        F: FnMut(bool, &mut App) + 'static;
172}
173
174impl FeatureFlagAppExt for App {
175    fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
176        let feature_flags = self.default_global::<FeatureFlags>();
177        feature_flags.staff = staff;
178        feature_flags.flags = flags;
179    }
180
181    fn set_staff(&mut self, staff: bool) {
182        let feature_flags = self.default_global::<FeatureFlags>();
183        feature_flags.staff = staff;
184    }
185
186    fn has_flag<T: FeatureFlag>(&self) -> bool {
187        self.try_global::<FeatureFlags>()
188            .map(|flags| flags.has_flag::<T>())
189            .unwrap_or(false)
190    }
191
192    fn is_staff(&self) -> bool {
193        self.try_global::<FeatureFlags>()
194            .map(|flags| flags.staff)
195            .unwrap_or(false)
196    }
197
198    fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
199    where
200        F: FnMut(bool, &mut App) + 'static,
201    {
202        self.observe_global::<FeatureFlags>(move |cx| {
203            let feature_flags = cx.global::<FeatureFlags>();
204            callback(feature_flags.has_flag::<T>(), cx);
205        })
206    }
207
208    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
209        let (tx, rx) = oneshot::channel::<bool>();
210        let mut tx = Some(tx);
211        let subscription: Option<Subscription>;
212
213        match self.try_global::<FeatureFlags>() {
214            Some(feature_flags) => {
215                subscription = None;
216                tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
217            }
218            None => {
219                subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
220                    let feature_flags = cx.global::<FeatureFlags>();
221                    if let Some(tx) = tx.take() {
222                        tx.send(feature_flags.has_flag::<T>()).ok();
223                    }
224                }));
225            }
226        }
227
228        WaitForFlag(rx, subscription)
229    }
230
231    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
232        let wait_for_flag = self.wait_for_flag::<T>();
233
234        self.spawn(async move |_cx| {
235            let mut wait_for_flag = wait_for_flag.fuse();
236            let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
237
238            select_biased! {
239                is_enabled = wait_for_flag => is_enabled,
240                _ = timeout => false,
241            }
242        })
243    }
244}
245
246pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
247
248impl Future for WaitForFlag {
249    type Output = bool;
250
251    fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
252        self.0.poll_unpin(cx).map(|result| {
253            self.1.take();
254            result.unwrap_or(false)
255        })
256    }
257}