feature_flags.rs

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