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