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