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 (cfg!(debug_assertions) || self.staff) && !*ZED_DISABLE_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 BillingV2FeatureFlag {}
65
66impl FeatureFlag for BillingV2FeatureFlag {
67 const NAME: &'static str = "billing-v2";
68}
69
70pub struct NotebookFeatureFlag;
71
72impl FeatureFlag for NotebookFeatureFlag {
73 const NAME: &'static str = "notebooks";
74}
75
76pub struct PanicFeatureFlag;
77
78impl FeatureFlag for PanicFeatureFlag {
79 const NAME: &'static str = "panic";
80}
81
82pub struct JjUiFeatureFlag {}
83
84impl FeatureFlag for JjUiFeatureFlag {
85 const NAME: &'static str = "jj-ui";
86}
87
88pub struct GeminiAndNativeFeatureFlag;
89
90impl FeatureFlag for GeminiAndNativeFeatureFlag {
91 // This was previously called "acp".
92 //
93 // We renamed it because existing builds used it to enable the Claude Code
94 // integration too, and we'd like to turn Gemini/Native on in new builds
95 // without enabling Claude Code in old builds.
96 const NAME: &'static str = "gemini-and-native";
97
98 fn enabled_for_all() -> bool {
99 true
100 }
101}
102
103pub struct ClaudeCodeFeatureFlag;
104
105impl FeatureFlag for ClaudeCodeFeatureFlag {
106 const NAME: &'static str = "claude-code";
107
108 fn enabled_for_all() -> bool {
109 true
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 {
148 self.defer_in(window, move |view, window, cx| {
149 callback(view, window, cx);
150 });
151 return;
152 }
153 let subscription = Rc::new(RefCell::new(None));
154 let inner = self.observe_global_in::<FeatureFlags>(window, {
155 let subscription = subscription.clone();
156 move |v, window, cx| {
157 let feature_flags = cx.global::<FeatureFlags>();
158 if feature_flags.has_flag::<T>() {
159 callback(v, window, cx);
160 subscription.take();
161 }
162 }
163 });
164 subscription.borrow_mut().replace(inner);
165 }
166}
167
168#[derive(Debug)]
169pub struct OnFlagsReady {
170 pub is_staff: bool,
171}
172
173pub trait FeatureFlagAppExt {
174 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag;
175
176 /// Waits for the specified feature flag to resolve, up to the given timeout.
177 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool>;
178
179 fn update_flags(&mut self, staff: bool, flags: Vec<String>);
180 fn set_staff(&mut self, staff: bool);
181 fn has_flag<T: FeatureFlag>(&self) -> bool;
182 fn is_staff(&self) -> bool;
183
184 fn on_flags_ready<F>(&mut self, callback: F) -> Subscription
185 where
186 F: FnMut(OnFlagsReady, &mut App) + 'static;
187
188 fn observe_flag<T: FeatureFlag, F>(&mut self, callback: F) -> Subscription
189 where
190 F: FnMut(bool, &mut App) + 'static;
191}
192
193impl FeatureFlagAppExt for App {
194 fn update_flags(&mut self, staff: bool, flags: Vec<String>) {
195 let feature_flags = self.default_global::<FeatureFlags>();
196 feature_flags.staff = staff;
197 feature_flags.flags = flags;
198 }
199
200 fn set_staff(&mut self, staff: bool) {
201 let feature_flags = self.default_global::<FeatureFlags>();
202 feature_flags.staff = staff;
203 }
204
205 fn has_flag<T: FeatureFlag>(&self) -> bool {
206 self.try_global::<FeatureFlags>()
207 .map(|flags| flags.has_flag::<T>())
208 .unwrap_or_else(|| {
209 (cfg!(debug_assertions) && T::enabled_for_staff() && !*ZED_DISABLE_STAFF)
210 || T::enabled_for_all()
211 })
212 }
213
214 fn is_staff(&self) -> bool {
215 self.try_global::<FeatureFlags>()
216 .map(|flags| flags.staff)
217 .unwrap_or(false)
218 }
219
220 fn on_flags_ready<F>(&mut self, mut callback: F) -> Subscription
221 where
222 F: FnMut(OnFlagsReady, &mut App) + 'static,
223 {
224 self.observe_global::<FeatureFlags>(move |cx| {
225 let feature_flags = cx.global::<FeatureFlags>();
226 callback(
227 OnFlagsReady {
228 is_staff: feature_flags.staff,
229 },
230 cx,
231 );
232 })
233 }
234
235 fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
236 where
237 F: FnMut(bool, &mut App) + 'static,
238 {
239 self.observe_global::<FeatureFlags>(move |cx| {
240 let feature_flags = cx.global::<FeatureFlags>();
241 callback(feature_flags.has_flag::<T>(), cx);
242 })
243 }
244
245 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
246 let (tx, rx) = oneshot::channel::<bool>();
247 let mut tx = Some(tx);
248 let subscription: Option<Subscription>;
249
250 match self.try_global::<FeatureFlags>() {
251 Some(feature_flags) => {
252 subscription = None;
253 tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
254 }
255 None => {
256 subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
257 let feature_flags = cx.global::<FeatureFlags>();
258 if let Some(tx) = tx.take() {
259 tx.send(feature_flags.has_flag::<T>()).ok();
260 }
261 }));
262 }
263 }
264
265 WaitForFlag(rx, subscription)
266 }
267
268 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
269 let wait_for_flag = self.wait_for_flag::<T>();
270
271 self.spawn(async move |_cx| {
272 let mut wait_for_flag = wait_for_flag.fuse();
273 let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
274
275 select_biased! {
276 is_enabled = wait_for_flag => is_enabled,
277 _ = timeout => false,
278 }
279 })
280 }
281}
282
283pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
284
285impl Future for WaitForFlag {
286 type Output = bool;
287
288 fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
289 self.0.poll_unpin(cx).map(|result| {
290 self.1.take();
291 result.unwrap_or(false)
292 })
293 }
294}