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