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 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 GeminiAndNativeFeatureFlag;
93
94impl FeatureFlag for GeminiAndNativeFeatureFlag {
95 // This was previously called "acp".
96 //
97 // We renamed it because existing builds used it to enable the Claude Code
98 // integration too, and we'd like to turn Gemini/Native on in new builds
99 // without enabling Claude Code in old builds.
100 const NAME: &'static str = "gemini-and-native";
101
102 fn enabled_for_all() -> bool {
103 true
104 }
105}
106
107pub struct ClaudeCodeFeatureFlag;
108
109impl FeatureFlag for ClaudeCodeFeatureFlag {
110 const NAME: &'static str = "claude-code";
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(T::enabled_for_all())
209 }
210
211 fn is_staff(&self) -> bool {
212 self.try_global::<FeatureFlags>()
213 .map(|flags| flags.staff)
214 .unwrap_or(false)
215 }
216
217 fn on_flags_ready<F>(&mut self, mut callback: F) -> Subscription
218 where
219 F: FnMut(OnFlagsReady, &mut App) + 'static,
220 {
221 self.observe_global::<FeatureFlags>(move |cx| {
222 let feature_flags = cx.global::<FeatureFlags>();
223 callback(
224 OnFlagsReady {
225 is_staff: feature_flags.staff,
226 },
227 cx,
228 );
229 })
230 }
231
232 fn observe_flag<T: FeatureFlag, F>(&mut self, mut callback: F) -> Subscription
233 where
234 F: FnMut(bool, &mut App) + 'static,
235 {
236 self.observe_global::<FeatureFlags>(move |cx| {
237 let feature_flags = cx.global::<FeatureFlags>();
238 callback(feature_flags.has_flag::<T>(), cx);
239 })
240 }
241
242 fn wait_for_flag<T: FeatureFlag>(&mut self) -> WaitForFlag {
243 let (tx, rx) = oneshot::channel::<bool>();
244 let mut tx = Some(tx);
245 let subscription: Option<Subscription>;
246
247 match self.try_global::<FeatureFlags>() {
248 Some(feature_flags) => {
249 subscription = None;
250 tx.take().unwrap().send(feature_flags.has_flag::<T>()).ok();
251 }
252 None => {
253 subscription = Some(self.observe_global::<FeatureFlags>(move |cx| {
254 let feature_flags = cx.global::<FeatureFlags>();
255 if let Some(tx) = tx.take() {
256 tx.send(feature_flags.has_flag::<T>()).ok();
257 }
258 }));
259 }
260 }
261
262 WaitForFlag(rx, subscription)
263 }
264
265 fn wait_for_flag_or_timeout<T: FeatureFlag>(&mut self, timeout: Duration) -> Task<bool> {
266 let wait_for_flag = self.wait_for_flag::<T>();
267
268 self.spawn(async move |_cx| {
269 let mut wait_for_flag = wait_for_flag.fuse();
270 let mut timeout = FutureExt::fuse(smol::Timer::after(timeout));
271
272 select_biased! {
273 is_enabled = wait_for_flag => is_enabled,
274 _ = timeout => false,
275 }
276 })
277 }
278}
279
280pub struct WaitForFlag(oneshot::Receiver<bool>, Option<Subscription>);
281
282impl Future for WaitForFlag {
283 type Output = bool;
284
285 fn poll(mut self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
286 self.0.poll_unpin(cx).map(|result| {
287 self.1.take();
288 result.unwrap_or(false)
289 })
290 }
291}