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