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