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