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