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