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 T::enabled_for_all() {
 23            return true;
 24        }
 25
 26        if self.staff && T::enabled_for_staff() {
 27            return true;
 28        }
 29
 30        self.flags.iter().any(|f| f.as_str() == T::NAME)
 31    }
 32}
 33
 34impl Global for FeatureFlags {}
 35
 36/// To create a feature flag, implement this trait on a trivial type and use it as
 37/// a generic parameter when called [`FeatureFlagAppExt::has_flag`].
 38///
 39/// Feature flags are enabled for members of Zed staff by default. To disable this behavior
 40/// so you can test flags being disabled, set ZED_DISABLE_STAFF=1 in your environment,
 41/// which will force Zed to treat the current user as non-staff.
 42pub trait FeatureFlag {
 43    const NAME: &'static str;
 44
 45    /// Returns whether this feature flag is enabled for Zed staff.
 46    fn enabled_for_staff() -> bool {
 47        true
 48    }
 49
 50    /// Returns whether this feature flag is enabled for everyone.
 51    ///
 52    /// This is generally done on the server, but we provide this as a way to entirely enable a feature flag client-side
 53    /// without needing to remove all of the call sites.
 54    fn enabled_for_all() -> bool {
 55        false
 56    }
 57}
 58
 59pub struct PredictEditsRateCompletionsFeatureFlag;
 60impl FeatureFlag for PredictEditsRateCompletionsFeatureFlag {
 61    const NAME: &'static str = "predict-edits-rate-completions";
 62}
 63
 64pub struct LlmClosedBetaFeatureFlag {}
 65impl FeatureFlag for LlmClosedBetaFeatureFlag {
 66    const NAME: &'static str = "llm-closed-beta";
 67}
 68
 69pub struct ZedProFeatureFlag {}
 70impl FeatureFlag for ZedProFeatureFlag {
 71    const NAME: &'static str = "zed-pro";
 72}
 73
 74pub struct NotebookFeatureFlag;
 75
 76impl FeatureFlag for NotebookFeatureFlag {
 77    const NAME: &'static str = "notebooks";
 78}
 79
 80pub struct ThreadAutoCaptureFeatureFlag {}
 81impl FeatureFlag for ThreadAutoCaptureFeatureFlag {
 82    const NAME: &'static str = "thread-auto-capture";
 83
 84    fn enabled_for_staff() -> bool {
 85        false
 86    }
 87}
 88pub struct PanicFeatureFlag;
 89
 90impl FeatureFlag for PanicFeatureFlag {
 91    const NAME: &'static str = "panic";
 92}
 93
 94pub struct JjUiFeatureFlag {}
 95
 96impl FeatureFlag for JjUiFeatureFlag {
 97    const NAME: &'static str = "jj-ui";
 98}
 99
100pub struct AcpFeatureFlag;
101
102impl FeatureFlag for AcpFeatureFlag {
103    const NAME: &'static str = "acp";
104}
105
106pub trait FeatureFlagViewExt<V: 'static> {
107    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
108    where
109        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
110
111    fn when_flag_enabled<T: FeatureFlag>(
112        &mut self,
113        window: &mut Window,
114        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
115    );
116}
117
118impl<V> FeatureFlagViewExt<V> for Context<'_, V>
119where
120    V: 'static,
121{
122    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
123    where
124        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + 'static,
125    {
126        self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
127            let feature_flags = cx.global::<FeatureFlags>();
128            callback(feature_flags.has_flag::<T>(), v, window, cx);
129        })
130    }
131
132    fn when_flag_enabled<T: FeatureFlag>(
133        &mut self,
134        window: &mut Window,
135        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
136    ) {
137        if self
138            .try_global::<FeatureFlags>()
139            .is_some_and(|f| f.has_flag::<T>())
140        {
141            self.defer_in(window, move |view, window, cx| {
142                callback(view, window, cx);
143            });
144            return;
145        }
146        let subscription = Rc::new(RefCell::new(None));
147        let inner = self.observe_global_in::<FeatureFlags>(window, {
148            let subscription = subscription.clone();
149            move |v, window, cx| {
150                let feature_flags = cx.global::<FeatureFlags>();
151                if feature_flags.has_flag::<T>() {
152                    callback(v, window, cx);
153                    subscription.take();
154                }
155            }
156        });
157        subscription.borrow_mut().replace(inner);
158    }
159}
160
161#[derive(Debug)]
162pub struct OnFlagsReady {
163    pub is_staff: bool,
164}
165
166pub trait FeatureFlagAppExt {
167    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
168
169    /// Waits for the specified feature flag to resolve, up to the given timeout.
170    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
171
172    fn update_flags(&mut self, staff: bool, flags: Vec<String>);
173    fn set_staff(&mut self, staff: bool);
174    fn has_flag<T: FeatureFlag>(&self) -> bool;
175    fn is_staff(&self) -> bool;
176
177    fn on_flags_ready<F>(&mut self, callback: F) -> Subscription
178    where
179        F: FnMut(OnFlagsReady, &mut App) + 'static;
180
181    fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
182    where
183        F: FnMut(bool, &mut App) + 'static;
184}
185
186impl FeatureFlagAppExt for App {
187    fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
188        let feature_flags = self.default_global::<FeatureFlags>();
189        feature_flags.staff = staff;
190        feature_flags.flags = flags;
191    }
192
193    fn set_staff(&mut self, staff: bool) {
194        let feature_flags = self.default_global::<FeatureFlags>();
195        feature_flags.staff = staff;
196    }
197
198    fn has_flag<T: FeatureFlag>(&self) -> bool {
199        self.try_global::<FeatureFlags>()
200            .map(|flags| flags.has_flag::<T>())
201            .unwrap_or(false)
202    }
203
204    fn is_staff(&self) -> bool {
205        self.try_global::<FeatureFlags>()
206            .map(|flags| flags.staff)
207            .unwrap_or(false)
208    }
209
210    fn on_flags_ready<F>(&mut self, mut callback: F) -> Subscription
211    where
212        F: FnMut(OnFlagsReady, &mut App) + 'static,
213    {
214        self.observe_global::<FeatureFlags>(move |cx| {
215            let feature_flags = cx.global::<FeatureFlags>();
216            callback(
217                OnFlagsReady {
218                    is_staff: feature_flags.staff,
219                },
220                cx,
221            );
222        })
223    }
224
225    fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
226    where
227        F: FnMut(bool, &mut App) + 'static,
228    {
229        self.observe_global::<FeatureFlags>(move |cx| {
230            let feature_flags = cx.global::<FeatureFlags>();
231            callback(feature_flags.has_flag::<T>(), cx);
232        })
233    }
234
235    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
236        let (tx, rx) = oneshot::channel::<bool>();
237        let mut tx = Some(tx);
238        let subscription: Option<Subscription>;
239
240        match self.try_global::<FeatureFlags>() {
241            Some(feature_flags) => {
242                subscription = None;
243                tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
244            }
245            None => {
246                subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
247                    let feature_flags = cx.global::<FeatureFlags>();
248                    if let Some(tx) = tx.take() {
249                        tx.send(feature_flags.has_flag::<T>()).ok();
250                    }
251                }));
252            }
253        }
254
255        WaitForFlag(rx, subscription)
256    }
257
258    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
259        let wait_for_flag = self.wait_for_flag::<T>();
260
261        self.spawn(async move |_cx| {
262            let mut wait_for_flag = wait_for_flag.fuse();
263            let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
264
265            select_biased! {
266                is_enabled = wait_for_flag => is_enabled,
267                _ = timeout => false,
268            }
269        })
270    }
271}
272
273pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
274
275impl Future for WaitForFlag {
276    type Output = bool;
277
278    fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
279        self.0.poll_unpin(cx).map(|result| {
280            self.1.take();
281            result.unwrap_or(false)
282        })
283    }
284}