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").is_ok_and(|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 PanicFeatureFlag;
 81
 82impl FeatureFlag for PanicFeatureFlag {
 83    const NAME: &'static str = "panic";
 84}
 85
 86pub struct JjUiFeatureFlag {}
 87
 88impl FeatureFlag for JjUiFeatureFlag {
 89    const NAME: &'static str = "jj-ui";
 90}
 91
 92pub struct AcpFeatureFlag;
 93
 94impl FeatureFlag for AcpFeatureFlag {
 95    const NAME: &'static str = "acp";
 96}
 97
 98pub struct ClaudeCodeFeatureFlag;
 99
100impl FeatureFlag for ClaudeCodeFeatureFlag {
101    const NAME: &'static str = "claude-code";
102}
103
104pub trait FeatureFlagViewExt<V: 'static> {
105    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
106    where
107        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static;
108
109    fn when_flag_enabled<T: FeatureFlag>(
110        &mut self,
111        window: &mut Window,
112        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
113    );
114}
115
116impl<V> FeatureFlagViewExt<V> for Context<'_, V>
117where
118    V: 'static,
119{
120    fn observe_flag<T: FeatureFlag, F>(&mut self, window: &Window, callback: F) -> Subscription
121    where
122        F: Fn(bool, &mut V, &mut Window, &mut Context<V>) + 'static,
123    {
124        self.observe_global_in::<FeatureFlags>(window, move |v, window, cx| {
125            let feature_flags = cx.global::<FeatureFlags>();
126            callback(feature_flags.has_flag::<T>(), v, window, cx);
127        })
128    }
129
130    fn when_flag_enabled<T: FeatureFlag>(
131        &mut self,
132        window: &mut Window,
133        callback: impl Fn(&mut V, &mut Window, &mut Context<V>) + Send + Sync + 'static,
134    ) {
135        if self
136            .try_global::<FeatureFlags>()
137            .is_some_and(|f| f.has_flag::<T>())
138        {
139            self.defer_in(window, move |view, window, cx| {
140                callback(view, window, cx);
141            });
142            return;
143        }
144        let subscription = Rc::new(RefCell::new(None));
145        let inner = self.observe_global_in::<FeatureFlags>(window, {
146            let subscription = subscription.clone();
147            move |v, window, cx| {
148                let feature_flags = cx.global::<FeatureFlags>();
149                if feature_flags.has_flag::<T>() {
150                    callback(v, window, cx);
151                    subscription.take();
152                }
153            }
154        });
155        subscription.borrow_mut().replace(inner);
156    }
157}
158
159#[derive(Debug)]
160pub struct OnFlagsReady {
161    pub is_staff: bool,
162}
163
164pub trait FeatureFlagAppExt {
165    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
166
167    /// Waits for the specified feature flag to resolve, up to the given timeout.
168    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
169
170    fn update_flags(&mut self, staff: bool, flags: Vec<String>);
171    fn set_staff(&mut self, staff: bool);
172    fn has_flag<T: FeatureFlag>(&self) -> bool;
173    fn is_staff(&self) -> bool;
174
175    fn on_flags_ready<F>(&mut self, callback: F) -> Subscription
176    where
177        F: FnMut(OnFlagsReady, &mut App) + 'static;
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 on_flags_ready<F>(&mut self, mut callback: F) -> Subscription
209    where
210        F: FnMut(OnFlagsReady, &mut App) + 'static,
211    {
212        self.observe_global::<FeatureFlags>(move |cx| {
213            let feature_flags = cx.global::<FeatureFlags>();
214            callback(
215                OnFlagsReady {
216                    is_staff: feature_flags.staff,
217                },
218                cx,
219            );
220        })
221    }
222
223    fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
224    where
225        F: FnMut(bool, &mut App) + 'static,
226    {
227        self.observe_global::<FeatureFlags>(move |cx| {
228            let feature_flags = cx.global::<FeatureFlags>();
229            callback(feature_flags.has_flag::<T>(), cx);
230        })
231    }
232
233    fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
234        let (tx, rx) = oneshot::channel::<bool>();
235        let mut tx = Some(tx);
236        let subscription: Option<Subscription>;
237
238        match self.try_global::<FeatureFlags>() {
239            Some(feature_flags) => {
240                subscription = None;
241                tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
242            }
243            None => {
244                subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
245                    let feature_flags = cx.global::<FeatureFlags>();
246                    if let Some(tx) = tx.take() {
247                        tx.send(feature_flags.has_flag::<T>()).ok();
248                    }
249                }));
250            }
251        }
252
253        WaitForFlag(rx, subscription)
254    }
255
256    fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
257        let wait_for_flag = self.wait_for_flag::<T>();
258
259        self.spawn(async move |_cx| {
260            let mut wait_for_flag = wait_for_flag.fuse();
261            let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
262
263            select_biased! {
264                is_enabled = wait_for_flag => is_enabled,
265                _ = timeout => false,
266            }
267        })
268    }
269}
270
271pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
272
273impl Future for WaitForFlag {
274    type Output = bool;
275
276    fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
277        self.0.poll_unpin(cx).map(|result| {
278            self.1.take();
279            result.unwrap_or(false)
280        })
281    }
282}