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