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